L3 Info : PHP et Applications Web
 
◃  Ch. 13 Symfony 7.4  ▹
 

Exemple : Création d'une entité auteur

  • Objectif : générer une table Auteur(aut_id, aut_nom, aut_prenom) et les classes Entity et Repository associées.

    $ php bin/console make:entity Auteur
    created: src/Entity/Auteur.php
    created: src/Repository/AuteurRepository.php
    Entity generated! Now lets add some fields!
    You can always add more fields later manually or by re-running this command.
    New property name (press <return> to stop adding fields):
    > aut_nom
    Field type (enter ? to see all types) [string]:
    > 
    Field length [255]:
    > 100
    Can this field be null in the database (nullable) (yes/no) [no]:
    > 
    updated: src/Entity/Auteur.php
    Add another property? Enter the property name (or press <return> to stop adding fields):
    > aut_prenom
    Field type (enter ? to see all types) [string]:
    > 
    Field length [255]:
    > 100
    Can this field be null in the database (nullable) (yes/no) [no]:
    > 
    updated: src/Entity/Auteur.php
    Add another property? Enter the property name (or press <return> to stop adding fields):
    > 
    
    Success! 
    
    Next: When you're ready, create a migration with php bin/console make:migration
  • Classe Entity/Auteur.php générée automatiquement par Symfony

    namespace App\Entity;
    
    use App\Repository\AuteurRepository;
    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity(repositoryClass: AuteurRepository::class)]
    class Auteur
    {
        #[ORM\Id]
        #[ORM\GeneratedValue]
        #[ORM\Column]
        private ?int $id = null;
    
        #[ORM\Column(length: 100)]
        private ?string $aut_nom = null;
    
        #[ORM\Column(length: 100)]
        private ?string $aut_prenom = null;
    
        public function getId(): ?int
        {
            return $this->id;
        }
    
        public function getAutNom(): ?string
        {
            return $this->aut_nom;
        }
    
        public function setAutNom(string $aut_nom): static
        {
            $this->aut_nom = $aut_nom;
    
            return $this;
        }
    
        public function getAutPrenom(): ?string
        {
            return $this->aut_prenom;
        }
    
        public function setAutPrenom(string $aut_prenom): static
        {
            $this->aut_prenom = $aut_prenom;
    
         return $this;
        }
    }
  • Classe Repository/AuteurRepository.php générée automatiquement par Symfony

    namespace App\Repository;
    
    use App\Entity\Auteur;
    use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
    use Doctrine\Persistence\ManagerRegistry;
    
    /**
    * @extends ServiceEntityRepository<Auteur>
    */
    class AuteurRepository extends ServiceEntityRepository
    {
        public function __construct(ManagerRegistry $registry)
        {
            parent::__construct($registry, Auteur::class);
        }
    
        //    /**
        //     * @return Auteur[] Returns an array of Auteur objects
        //     */
        //    public function findByExampleField($value): array
        //    {
        //        return $this->createQueryBuilder('a')
        //            ->andWhere('a.exampleField = :val')
        //            ->setParameter('val', $value)
        //            ->orderBy('a.id', 'ASC')
        //            ->setMaxResults(10)
        //            ->getQuery()
        //            ->getResult()
        //        ;
        //    }
    
        //    public function findOneBySomeField($value): ?Auteur
        //    {
        //        return $this->createQueryBuilder('a')
        //            ->andWhere('a.exampleField = :val')
        //            ->setParameter('val', $value)
        //            ->getQuery()
        //            ->getOneOrNullResult()
        //        ;
        //    }
    }
  • Préparation de la migration :

    $ php bin/console make:migration
    created: migrations/Version20260301170811.php
    
    Success!
    
    Review the new migration then run it with php bin/console doctrine:migrations:migrate
    See https://symfony.com/doc/current/bundles/DoctrineMigrationsBundle/index.html
  • Fichier de migration migrations/Versionyyyymmddhhmmss.php :

    namespace DoctrineMigrations;
    
    use Doctrine\DBAL\Schema\Schema;
    use Doctrine\Migrations\AbstractMigration;
    
    /**
    * Auto-generated Migration: Please modify to your needs!
    */
    final class Version20260301170811 extends AbstractMigration
    {
        public function getDescription(): string
        {
            return '';
        }
    
        public function up(Schema $schema): void
        {
            // this up() migration is auto-generated, please modify it to your needs
            $this->addSql('CREATE TABLE auteur (id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL, 
                                aut_nom VARCHAR(100) NOT NULL, 
                                aut_prenom VARCHAR(100) NOT NULL, 
                                PRIMARY KEY (id))');
        }
    
        public function down(Schema $schema): void
        {
            // this down() migration is auto-generated, please modify it to your needs
            $this->addSql('DROP TABLE auteur');
        }
    }
  • Réalisation de la migration :

        $ php bin/console doctrine:migrations:migrate
        WARNING! You are about to execute a migration in database "symfony_db" that could result in schema changes and data loss. Are you sure you wish to continue? (yes/no) [yes]:
        > 
    
        [notice] Migrating up to DoctrineMigrations\Version20260301170811
        [notice] finished in 17.5ms, used 24M memory, 1 migrations executed, 1 sql queries
    
        [OK] Successfully migrated to version: DoctrineMigrations\Version20260301170811                                        
  • La table Auteur est créée !