Loading...

Working with Doctrine Symfony Part 2 - Creating Entities, creating fields, doing migrations

So, we have our Doctrine setup done, we will start creating Entities

In the previous post we set up our project to support doctrine, so, in this one, we will be adding entities and seeing how they behave.

If you look in the config/packages/doctrine.yaml, you will see that under orm you have mappings/App/dir. This is important, since all the entities must be in this folder. This is important since Doctrine will look inside that folder for any entity changes. So, we will start by creating a BaseEntity object and adding basic properties that all our entities will extend:

<?php

namespace App\Entity;

use DateTime;
use Doctrine\ORM\Mapping as ORM;

/**
 * Class BaseEntity
 * @package App\Entity
 */
class BaseEntity
{
    /**
     * @var int $id
     *
     * @ORM\Id;
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var DateTime $created_at
     *
     * @ORM\Column(type="datetime")
     */
    protected $created_at;

    /**
     * @var DateTime $updated_at
     *
     * @ORM\Column(type="datetime")
     */
    protected $updated_at;

    /**
     * @return int
     */
    public function getId(): int
    {
        return $this->id;
    }

    /**
     * @param int $id
     */
    public function setId(int $id): void
    {
        $this->id = $id;
    }

    /**
     * @param DateTime $created_at
     */
    public function setCreatedAt(DateTime $created_at): void
    {
        $this->created_at = $created_at;
    }

    /**
     * @return DateTime
     */
    public function getCreatedAt(): DateTime
    {
        return $this->created_at;
    }

    /**
     * @param DateTime $updated_at
     */
    public function setUpdatedAt(DateTime $updated_at): void
    {
        $this->updated_at = $updated_at;
    }

    /**
     * @return DateTime
     */
    public function getUpdatedAt(): DateTime
    {
        return $this->updated_at;
    }

    /**
     *
     * @ORM\PrePersist
     * @ORM\PreUpdate
     */
    public function updatedTimestamps(): void
    {
        $this->setUpdatedAt(new \DateTime('now'));

        if ($this->getCreatedAt() == null) {
            $this->setCreatedAt(new \DateTime('now'));
        }
    }
}

So, to understand what is going on:
We are creating the BaseEntity class in order to extend all of the other Entities that we will create. This is done because all the other Entities will have id, created_at and updated_at. We are also using @ORM\PrePersist and @ORM\PreUpdate to create and updated created_at and updated_at, since we don't want to it manually.

Next, we will create our User Entity object:

<?php


namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Class User
 * @ORM\Entity()
 * @ORM\HasLifecycleCallbacks
 * @package App\Entity
 */
class User extends BaseEntity
{

    /**
     * @var string $name
     * @ORM\Column(type="string", length=128, unique=false, nullable=false)
     */
    protected $name;

    /**
     * @var string $email
     * @ORM\Column(type="string", length=128, unique=false, nullable=false)
     */
    protected $email;

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @param string $name
     */
    public function setName(string $name): void
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getEmail(): string
    {
        return $this->email;
    }

    /**
     * @param string $email
     */
    public function setEmail(string $email): void
    {
        $this->email = $email;
    }
}

As you can see, we are extending our User Entity class with BaseEntity class so we can access all the properties from BaseEntity.

Now, we will create our first migration. Open up your terminal and type:

bin/console doctrine:migrations:diff

Now, you will see that new Migration class is generated in src/Migrations. It will look something like this:

<?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 Version20190523190207 extends AbstractMigration
{
    /**
     * @return string
     */
    public function getDescription(): string
    {
        return '';
    }

    /**
     * @param Schema $schema
     * @throws \Doctrine\DBAL\DBALException
     */
    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 user (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(128) NOT NULL, email VARCHAR(128) NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');
    }

    /**
     * @param Schema $schema
     * @throws \Doctrine\DBAL\DBALException
     */
    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 user');
    }
}

And now, we can migrate and update our database with our Entity data and structure. Please run:

 bin/console doctrine:migrations:migrate

Voila! You have successfully executed migration, take a look in your SQL and you will see that there is a new table called user

Comments (0)

Leave a comment

Dire Solutions Logo Dark Vertical