Step 8: Describing the Data Structure

Describing the Data Structure

This command installs a few dependencies: Doctrine DBAL (a database abstraction layer), Doctrine ORM (a library to manipulate our database content using PHP objects), and Doctrine Migrations.

How does Doctrine know the database connection? Doctrine’s recipe added a configuration file, , that controls its behavior. The main setting is the database DSN, a string containing all the information about the connection: credentials, host, port, etc. By default, Doctrine looks for a DATABASE_URL environment variable.

Almost all installed packages have a configuration under the config/packages/ directory. Most of the time, the defaults have been chosen carefully to work for most applications.

Understanding Symfony Environment Variable Conventions

You can define the DATABASE_URL manually in the .env or .env.local file. In fact, thanks to the package’s recipe, you’ll see an example DATABASE_URL in your .env file. But because the local port to PostgreSQL exposed by Docker can change, it is quite cumbersome. There is a better way.

Instead of hard-coding DATABASE_URL in a file, we can prefix all commands with symfony. This will detect services ran by Docker and/or SymfonyCloud (when the tunnel is open) and set the environment variable automatically.

Docker Compose and SymfonyCloud work seamlessly with Symfony thanks to these environment variables.

Check all exposed environment variables by executing symfony var:export:

  1. $ symfony var:export
  1. DATABASE_URL=postgres://main:[email protected]:32781/main?sslmode=disable&charset=utf8
  2. # ...

Remember the database service name used in the Docker and SymfonyCloud configurations? The service names are used as prefixes to define environment variables like DATABASE_URL. If your services are named according to the Symfony conventions, no other configuration is needed.

Note

Databases are not the only service that benefit from the Symfony conventions. The same goes for Mailer, for example (via the MAILER_DSN environment variable).

Changing the Default DATABASE_URL Value in .env

We will still change the .env file to setup the default DATABASE_URL to use PostgreSQL:

  1. --- a/.env
  2. +++ b/.env
  3. @@ -24,5 +24,5 @@ APP_SECRET=ce2ae8138936039d22afb20f4596fe97
  4. #
  5. # DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
  6. # DATABASE_URL="mysql://db_user:[email protected]:3306/db_name?serverVersion=5.7"
  7. -DATABASE_URL="postgresql://db_user::5432/db_name?serverVersion=13&charset=utf8"
  8. +DATABASE_URL="postgresql://127.0.0.1:5432/db?serverVersion=13&charset=utf8"
  9. ###< doctrine/doctrine-bundle ###

Why does the information need to be duplicated in two different places? Because on some Cloud platforms, at build time, the database URL might not be known yet but Doctrine needs to know the database’s engine to build its configuration. So, the host, username, and password do not really matter.

A conference can be described with a few properties:

  • The city where the conference is organized;
  • The year of the conference;
  • An international flag to indicate if the conference is local or international (SymfonyLive vs SymfonyCon).

The Maker bundle can help us generate a class (an Entity class) that represents a conference:

  1. $ symfony console make:entity Conference
  • city, string, 255, no;
  • year, string, 4, no;
  • isInternational, boolean, no.

Here is the full output when running the command:

The Conference class has been stored under the App\Entity\ namespace.

The command also generated a Doctrine repository class: App\Repository\ConferenceRepository.

The generated code looks like the following (only a small portion of the file is replicated here):

src/App/Entity/Conference.php

  1. namespace App\Entity;
  2. use App\Repository\ConferenceRepository;
  3. use Doctrine\ORM\Mapping as ORM;
  4. /**
  5. * @ORM\Entity(repositoryClass=ConferenceRepository::class)
  6. */
  7. class Conference
  8. {
  9. /**
  10. * @ORM\Id()
  11. * @ORM\GeneratedValue()
  12. * @ORM\Column(type="integer")
  13. */
  14. private $id;
  15. /**
  16. * @ORM\Column(type="string", length=255)
  17. */
  18. private $city;
  19. // ...
  20. public function getCity(): ?string
  21. {
  22. return $this->city;
  23. }
  24. public function setCity(string $city): self
  25. {
  26. $this->city = $city;
  27. return $this;
  28. }
  29. // ...
  30. }

Note that the class itself is a plain PHP class with no signs of Doctrine. Annotations are used to add metadata useful for Doctrine to map the class to its related database table.

Doctrine added an id property to store the primary key of the row in the database table. This key (@ORM\Id()) is automatically generated (@ORM\GeneratedValue()) via a strategy that depends on the database engine.

Now, generate an Entity class for conference comments:

  1. $ symfony console make:entity Comment

Enter the following answers:

  • text, text, no;
  • email, string, 255, no;
  • createdAt, datetime, no.

Linking Entities

The two entities, Conference and Comment, should be linked together. A Conference can have zero or more Comments, which is called a one-to-many relationship.

Use the make:entity command again to add this relationship to the Conference class:

  1. $ symfony console make:entity Conference
  1. Your entity already exists! So let's add some new fields!
  2. New property name (press <return> to stop adding fields):
  3. > comments
  4. Field type (enter ? to see all types) [string]:
  5. > OneToMany
  6. What class should this entity be related to?:
  7. > Comment
  8. A new property will also be added to the Comment class...
  9. New field name inside Comment [conference]:
  10. >
  11. Is the Comment.conference property allowed to be null (nullable)? (yes/no) [yes]:
  12. > no
  13. Do you want to activate orphanRemoval on your relationship?
  14. A Comment is "orphaned" when it is removed from its related Conference.
  15. e.g. $conference->removeComment($comment)
  16. NOTE: If a Comment may *change* from one Conference to another, answer "no".
  17. Do you want to automatically delete orphaned App\Entity\Comment objects (orphanRemoval)? (yes/no) [no]:
  18. > yes
  19. updated: src/Entity/Conference.php
  20. updated: src/Entity/Comment.php

Note

If you enter ? as an answer for the type, you will get all supported types:

Have a look at the full diff for the entity classes after adding the relationship:

  1. --- a/src/Entity/Comment.php
  2. +++ b/src/Entity/Comment.php
  3. @@ -36,6 +36,12 @@ class Comment
  4. */
  5. private $createdAt;
  6. + /**
  7. + * @ORM\ManyToOne(targetEntity=Conference::class, inversedBy="comments")
  8. + * @ORM\JoinColumn(nullable=false)
  9. + */
  10. + private $conference;
  11. +
  12. public function getId(): ?int
  13. {
  14. return $this->id;
  15. @@ -88,4 +94,16 @@ class Comment
  16. return $this;
  17. }
  18. +
  19. + public function getConference(): ?Conference
  20. + {
  21. + return $this->conference;
  22. + }
  23. +
  24. + public function setConference(?Conference $conference): self
  25. + {
  26. + $this->conference = $conference;
  27. +
  28. + return $this;
  29. + }
  30. }
  31. --- a/src/Entity/Conference.php
  32. +++ b/src/Entity/Conference.php
  33. @@ -2,6 +2,8 @@
  34. namespace App\Entity;
  35. +use Doctrine\Common\Collections\ArrayCollection;
  36. +use Doctrine\Common\Collections\Collection;
  37. use Doctrine\ORM\Mapping as ORM;
  38. /**
  39. @@ -31,6 +33,16 @@ class Conference
  40. private $isInternational;
  41. + /**
  42. + * @ORM\OneToMany(targetEntity=Comment::class, mappedBy="conference", orphanRemoval=true)
  43. + */
  44. + private $comments;
  45. +
  46. + public function __construct()
  47. + {
  48. + $this->comments = new ArrayCollection();
  49. + }
  50. +
  51. public function getId(): ?int
  52. {
  53. return $this->id;
  54. @@ -71,4 +83,35 @@ class Conference
  55. return $this;
  56. }
  57. +
  58. + /**
  59. + * @return Collection|Comment[]
  60. + */
  61. + public function getComments(): Collection
  62. + {
  63. + return $this->comments;
  64. + }
  65. +
  66. + public function addComment(Comment $comment): self
  67. + {
  68. + if (!$this->comments->contains($comment)) {
  69. + $this->comments[] = $comment;
  70. + $comment->setConference($this);
  71. + }
  72. +
  73. + return $this;
  74. + }
  75. +
  76. + public function removeComment(Comment $comment): self
  77. + {
  78. + if ($this->comments->contains($comment)) {
  79. + $this->comments->removeElement($comment);
  80. + // set the owning side to null (unless already changed)
  81. + if ($comment->getConference() === $this) {
  82. + $comment->setConference(null);
  83. + }
  84. + }
  85. +
  86. + return $this;
  87. + }
  88. }

Adding more Properties

I just realized that we have forgotten to add one property on the Comment entity: attendees might want to attach a photo of the conference to illustrate their feedback.

Run make:entity once more and add a photoFilename property/column of type string, but allow it to be null as uploading a photo is optional:

  1. $ symfony console make:entity Comment

The project model is now fully described by the two generated classes.

Next, we need to create the database tables related to these PHP entities.

Doctrine Migrations is the perfect match for such a task. It has already been installed as part of the orm dependency.

A migration is a class that describes the changes needed to update a database schema from its current state to the new one defined by the entity annotations. As the database is empty for now, the migration should consist of two table creations.

Let’s see what Doctrine generates:

  1. $ symfony console make:migration

Notice the generated file name in the output (a name that looks like migrations/Version20191019083640.php):

migrations/Version20191019083640.php

  1. namespace DoctrineMigrations;
  2. use Doctrine\DBAL\Schema\Schema;
  3. use Doctrine\Migrations\AbstractMigration;
  4. final class Version20191019083640 extends AbstractMigration
  5. {
  6. public function up(Schema $schema) : void
  7. {
  8. // this up() migration is auto-generated, please modify it to your needs
  9. $this->addSql('CREATE SEQUENCE comment_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
  10. $this->addSql('CREATE SEQUENCE conference_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
  11. $this->addSql('CREATE TABLE comment (id INT NOT NULL, conference_id INT NOT NULL, author VARCHAR(255) NOT NULL, text TEXT NOT NULL, email VARCHAR(255) NOT NULL, created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, photo_filename VARCHAR(255) DEFAULT NULL, PRIMARY KEY(id))');
  12. $this->addSql('CREATE INDEX IDX_9474526C604B8382 ON comment (conference_id)');
  13. $this->addSql('CREATE TABLE conference (id INT NOT NULL, city VARCHAR(255) NOT NULL, year VARCHAR(4) NOT NULL, is_international BOOLEAN NOT NULL, PRIMARY KEY(id))');
  14. $this->addSql('ALTER TABLE comment ADD CONSTRAINT FK_9474526C604B8382 FOREIGN KEY (conference_id) REFERENCES conference (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
  15. }
  16. public function down(Schema $schema) : void
  17. {
  18. // ...
  19. }
  20. }

Updating the Local Database

You can now run the generated migration to update the local database schema:

The local database schema is now up-to-date, ready to store some data.

Updating the Production Database

The steps needed to migrate the production database are the same as the ones you are already familiar with: commit the changes and deploy.

When deploying the project, SymfonyCloud updates the code, but also runs the database migration if any (it detects if the doctrine:migrations:migrate command exists).

Going Further