Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Prochaine révision
Révision précédente
prog:symfony:entities:entity [27/10/2019 13:51]
thierry créée
prog:symfony:entities:entity [13/09/2022 16:17] (Version actuelle)
thierry [Création]
Ligne 1: Ligne 1:
 ====== Symfony et les Entities (Entity)====== ====== Symfony et les Entities (Entity)======
 +===== Prérequis =====
  
-===== Types de champs =====+Avant de jouer avec les Entities il faut que la [[prog:​symfony:​doctrine:​databases|base de données soit paramétrée et créée]]. 
 + 
 +-> Source : [[https://​symfony.com/​doc/​current/​doctrine.html#​configuring-the-database]] 
 + 
 +===== Entity ===== 
 + 
 +Une Entity est un **Objet PHP** qui sera stocké en base de donnée via l'ORM de Symfony 
 + 
 +Pour créer une Entity on utilisera la commande ''​symfony console make:entity %EntityName%''​ (voir ci-dessous). 
 + 
 +-> Source : [[https://​symfony.com/​doc/​current/​doctrine.html#​creating-an-entity-class]] 
 + 
 +===== Création d'une Entity ===== 
 +Le but ici est de créé une ''​entity''​ avec les champs ​suivants: 
 +  * **Name** : string 
 +  * **Url** : string 
 +  * **VMaj** : integer 
 +  * **VMin**: integer 
 +  * **Revision** : integer 
 +  * **Construction** : integer 
 +  * **Online_Date** : Date 
 +===make:​entity ​==== 
 +Avec la console ''​php bin\console make:​entity''​ ou  ''​symfony console make:​entity''​
 <​code>​ <​code>​
 +D:​\webprojects\test-api-project>​php bin\console make:entity
 +
 + Class name of the entity to create or update (e.g. BraveGnome):​
 + > Projects ​
 +
 + ​created:​ src/​Entity/​Projects.php
 + ​created:​ src/​Repository/​ProjectsRepository.php
 + 
 + ​Entity generated! Now let's 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):
 + > name
 +
 + Field type (enter ? to see all types) [string]:
 + > string
 +
 + Field length [255]:
 + > 40
 +
 + Can this field be null in the database (nullable) (yes/no) [no]:
 + > no
 +
 + ​updated:​ src/​Entity/​Projects.php
 +
 + Add another property? Enter the property name (or press <​return>​ to stop adding fields):
 + > url
 +
 + Field type (enter ? to see all types) [string]:
 + > string
 +
 + Field length [255]:
 + > ​
 +
 + Can this field be null in the database (nullable) (yes/no) [no]:
 + > no
 +
 + ​updated:​ src/​Entity/​Projects.php
 +
 + Add another property? Enter the property name (or press <​return>​ to stop adding fields):
 + > vmaj
 +
 + Field type (enter ? to see all types) [string]:
 + > integer
 +
 + Can this field be null in the database (nullable) (yes/no) [no]:
 + > ​
 +
 + ​updated:​ src/​Entity/​Projects.php
 +
 + Add another property? Enter the property name (or press <​return>​ to stop adding fields):
 + > vmin
 +
 + Field type (enter ? to see all types) [string]:
 + > integer
 +
 + Can this field be null in the database (nullable) (yes/no) [no]:
 + >
 +
 + ​updated:​ src/​Entity/​Projects.php
 +
 + Add another property? Enter the property name (or press <​return>​ to stop adding fields):
 + > revision
 +
 + Field type (enter ? to see all types) [string]:
 + > integer
 +
 + Can this field be null in the database (nullable) (yes/no) [no]:
 + >
 +
 + ​updated:​ src/​Entity/​Projects.php
 +
 + Add another property? Enter the property name (or press <​return>​ to stop adding fields):
 + > construction
 +
 + Field type (enter ? to see all types) [string]:
 + > integer
 +
 + Can this field be null in the database (nullable) (yes/no) [no]:
 + >
 +
 + ​updated:​ src/​Entity/​Projects.php
 +
 + Add another property? Enter the property name (or press <​return>​ to stop adding fields):
 + > online_date
 +
 + Field type (enter ? to see all types) [string]:
 + > date
 +
 + Can this field be null in the database (nullable) (yes/no) [no]:
 + >
 +
 + ​updated:​ src/​Entity/​Projects.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 make:​migration
 +</​code>​
 +=== Types de champs possibles===
 Main types Main types
   * string   * string
Ligne 35: Ligne 163:
   * decimal   * decimal
   * guid   * guid
 +
 +=== Fichier Entity généré ===
 +<code php src\Entity\Projects.php>​
 +<?php
 +
 +namespace App\Entity;
 +
 +use Doctrine\ORM\Mapping as ORM;
 +
 +/**
 + * @ORM\Entity(repositoryClass="​App\Repository\ProjectsRepository"​)
 + */
 +class Projects
 +{
 +    /**
 +     * @ORM\Id()
 +     * @ORM\GeneratedValue()
 +     * @ORM\Column(type="​integer"​)
 +     */
 +    private $id;
 +
 +    /**
 +     * @ORM\Column(type="​string",​ length=40)
 +     */
 +    private $name;
 +
 +    /**
 +     * @ORM\Column(type="​string",​ length=255)
 +     */
 +    private $url;
 +
 +    /**
 +     * @ORM\Column(type="​integer"​)
 +     */
 +    private $vmaj;
 +
 +    /**
 +     * @ORM\Column(type="​integer"​)
 +     */
 +    private $vmin;
 +
 +    /**
 +     * @ORM\Column(type="​integer"​)
 +     */
 +    private $revision;
 +
 +    /**
 +     * @ORM\Column(type="​integer"​)
 +     */
 +    private $construction;​
 +
 +    /**
 +     * @ORM\Column(type="​date"​)
 +     */
 +    private $online_date;​
 +
 +    public function getId(): ?int
 +    {
 +        return $this->​id;​
 +    }
 +
 +    public function getName(): ?string
 +    {
 +        return $this->​name;​
 +    }
 +
 +    public function setName(string $name): self
 +    {
 +        $this->​name = $name;
 +
 +        return $this;
 +    }
 +
 +    public function getUrl(): ?string
 +    {
 +        return $this->​url;​
 +    }
 +
 +    public function setUrl(string $url): self
 +    {
 +        $this->​url = $url;
 +
 +        return $this;
 +    }
 +
 +    public function getVmaj(): ?int
 +    {
 +        return $this->​vmaj;​
 +    }
 +
 +    public function setVmaj(int $vmaj): self
 +    {
 +        $this->​vmaj = $vmaj;
 +
 +        return $this;
 +    }
 +
 +    public function getVmin(): ?int
 +    {
 +        return $this->​vmin;​
 +    }
 +
 +    public function setVmin(int $vmin): self
 +    {
 +        $this->​vmin = $vmin;
 +
 +        return $this;
 +    }
 +
 +    public function getRevision():​ ?int
 +    {
 +        return $this->​revision;​
 +    }
 +
 +    public function setRevision(int $revision): self
 +    {
 +        $this->​revision = $revision;
 +
 +        return $this;
 +    }
 +
 +    public function getConstruction():​ ?int
 +    {
 +        return $this->​construction;​
 +    }
 +
 +    public function setConstruction(int $construction):​ self
 +    {
 +        $this->​construction = $construction;​
 +
 +        return $this;
 +    }
 +
 +    public function getOnlineDate():​ ?​\DateTimeInterface
 +    {
 +        return $this->​online_date;​
 +    }
 +
 +    public function setOnlineDate(\DateTimeInterface $online_date):​ self
 +    {
 +        $this->​online_date = $online_date;​
 +
 +        return $this;
 +    }
 +}
 +
 </​code>​ </​code>​
 +=== Fichier Repository généré ===
 +<code php src/​Repository/​ProjectsRepository.php>​
 +<?php
 +
 +namespace App\Repository;​
 +
 +use App\Entity\Projects;​
 +use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;​
 +use Doctrine\Common\Persistence\ManagerRegistry;​
 +
 +/**
 + * @method Projects|null find($id, $lockMode = null, $lockVersion = null)
 + * @method Projects|null findOneBy(array $criteria, array $orderBy = null)
 + * @method Projects[] ​   findAll()
 + * @method Projects[] ​   findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 + */
 +class ProjectsRepository extends ServiceEntityRepository
 +{
 +    public function __construct(ManagerRegistry $registry)
 +    {
 +        parent::​__construct($registry,​ Projects::​class);​
 +    }
 +
 +    // /**
 +    //  * @return Projects[] Returns an array of Projects objects
 +    //  */
 +    /*
 +    public function findByExampleField($value)
 +    {
 +        return $this->​createQueryBuilder('​p'​)
 +            ->​andWhere('​p.exampleField = :val')
 +            ->​setParameter('​val',​ $value)
 +            ->​orderBy('​p.id',​ '​ASC'​)
 +            ->​setMaxResults(10)
 +            ->​getQuery()
 +            ->​getResult()
 +        ;
 +    }
 +    */
 +
 +    /*
 +    public function findOneBySomeField($value):​ ?Projects
 +    {
 +        return $this->​createQueryBuilder('​p'​)
 +            ->​andWhere('​p.exampleField = :val')
 +            ->​setParameter('​val',​ $value)
 +            ->​getQuery()
 +            ->​getOneOrNullResult()
 +        ;
 +    }
 +    */
 +}
 +
 +</​code>​
 +
 +
 +
 +==== make:​migration ====
 +<​code>​
 +D:​\webprojects\test-api-project>​php bin/console make:​migration
 +
 +  Success!
 +
 +
 + Next: Review the new migration "​src/​Migrations/​Version20191027131103.php"​
 + Then: Run the migration with php bin/console doctrine:​migrations:​migrate
 + See https://​symfony.com/​doc/​current/​bundles/​DoctrineMigrationsBundle/​index.html
 +</​code>​
 +Voir : [[https://​symfony.com/​doc/​current/​bundles/​DoctrineMigrationsBundle/​index.html]]
 +=== Fichier de migration généré ===
 +<code php src/​Migrations/​Version20191027131103.php>​
 +<?php
 +
 +declare(strict_types=1);​
 +
 +namespace DoctrineMigrations;​
 +
 +use Doctrine\DBAL\Schema\Schema;​
 +use Doctrine\Migrations\AbstractMigration;​
 +
 +/**
 + * Auto-generated Migration: Please modify to your needs!
 + */
 +final class Version20191027131103 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->​abortIf($this->​connection->​getDatabasePlatform()->​getName() !== '​mysql',​ '​Migration can only be executed safely on \'​mysql\'​.'​);​
 +
 +        $this->​addSql('​CREATE TABLE projects (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(40) NOT NULL, url VARCHAR(255) NOT NULL, vmaj INT NOT NULL, vmin INT NOT NULL, revision INT NOT NULL, construction INT NOT NULL, online_date DATE NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB'​);​
 +    }
 +
 +    public function down(Schema $schema) : void
 +    {
 +        // this down() migration is auto-generated,​ please modify it to your needs
 +        $this->​abortIf($this->​connection->​getDatabasePlatform()->​getName() !== '​mysql',​ '​Migration can only be executed safely on \'​mysql\'​.'​);​
 +
 +        $this->​addSql('​DROP TABLE projects'​);​
 +    }
 +}
 +
 +</​code>​
 +
 +==== doctrine:​migrations:​migrate ====
 +<​code>​
 +D:​\webprojects\test-api-project>​php bin/console doctrine:​migrations:​migrate
 +
 +                    Application Migrations
 +
 +
 +WARNING! You are about to execute a database migration that could result in schema changes and data loss. 
 +Are you sure you wish to continue? (y/n)y
 +Migrating up to 20191027131103 from 0
 +
 +  ++ migrating 20191027131103
 +
 +     -> CREATE TABLE projects (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(40) NOT NULL, url VARCHAR(255) NOT NULL, vmaj INT NOT NULL, vmin INT NOT NULL, revision INT NOT NULL, construction INT NOT NULL, online_date DATE NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB
 +
 +  ++ migrated (took 557.6ms, used 16M memory)
 +
 +  ------------------------
 +
 +  ++ finished in 569.9ms
 +  ++ used 16M memory
 +  ++ 1 migrations executed
 +  ++ 1 sql queries
 +
 +</​code>​
 +=== Résultats de la migration ===
 +{{:​prog:​symfony:​table_projetcs.png|}}
 +====== Resources ======
 +  * [[https://​symfony.com/​doc/​current/​doctrine.html]]
 +
 +
 +
 +
 +