Organizing SCRUD code in Symfony 5 - Part 1/3
Writing SCRUD (search, create, read, update, delete) code is a very common thing to do when working on your back-end. The SCRUD logic spans the entire MVC (Model, View, Controller) architecture, all the way from API endpoints to database systems.
This post will describe how I organize this code in my Symfony applications to make it clear and performant. The use case for this example is simple: I want to manage blog posts in a database using an API.
It always starts with the database layer. Symfony leverages a tool called Doctrine to abstract away interactions with the database. You just create an object called an Entity, and Doctrine will take care of giving you an API to manage the rows of the relevant tables.
src\Entity\BlogPost.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/** * @ORM\Entity
* @ORM\Table(name="Text")
*/
class Text{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", length=50, unique=true, nullable=true)
*/
protected $uuid;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
protected $published_datetime;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
protected $title;
/**
* @ORM\Column(type="text", nullable=true)
*/
protected $content;
public function __construct(){
$this->uuid = Uuid::uuid4()->toString();
}
// GETTERS
public function getId(){
return $this->id;
}
public function getUUId(){
return $this->uuid;
}
public function getPublishedDatetime(){
return $this->published_datetime;
}
public function getTitle(){
return $this->title;
}
public function getContent(){
return $this->content;
}
// SETTERS
public function setPublishedDatetime($published_datetime){
$this->published_datetime = $published_datetime;
return $this;
}
public function setTitle($title){
$this->title = $title;
return $this;
}
public function setContent($content){
$this->content = $content;
return $this;
}
// FUNCTIONS
public function toArray(){
return [
'id' => $this->id,
'uuid' => $this->uuid,
'published_datetime' => $this->getPublishedDatetime()->format('Y-m-d H:i:s'),
'title' => $this->title,
'content' => $this->content
];
}
public function toJSON(){
return json_encode($this->toArray());
}
public function __toString(){
return json_encode($this->toArray());
}
}
?>
The Entity classes contain table fields in the form of protected properties, as well as getters and setters. I also usually add some functions, like toArray(), which are often used to send data to a Javascript client. Doctrine can consume Entity classes to generate SQL code that will be used to manage our database.