Entities
| An entity class | |
| Map columns | |
| Ids that generate | |
| Repository class |
An entity class
An entity is a PHP class mapped to one database table. Doctrine reads the attributes and builds the schema from them. Entities live in src/Entity:
namespace App\Entity; use Doctrine\ORM\Mapping as ORM; #[ORM\Entity] class Post { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; }
Map columns
Every property becomes a table column. Options like length and type tune the column without touching SQL:
use Doctrine\ORM\Mapping as ORM; class Post { #[ORM\Column(length: 255)] private string $title = ""; #[ORM\Column(type: "text")] private string $body = ""; }
Ids that generate
The id property is special. GeneratedValue tells the database to number new rows itself, so your code never assigns it. A getter exposes it for reading:
class Post { public function getId(): ?int { return $this->id; } public function getTitle(): string { return $this->title; } }
Repository class
Each entity gets a repository class for queries. It extends the base repository and receives the registry through its constructor, exactly as the entity generator writes it:
namespace App\Repository; use App\Entity\Post; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; class PostRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Post::class); } }
Next: Migrations
Article author: Arthur Isaev