Step 13: Managing the Lifecycle of Doctrine Objects

Managing the Lifecycle of Doctrine Objects

When creating a new comment, it would be great if the createdAt date would be set automatically to the current date and time.

Doctrine has different ways to manipulate objects and their properties during their lifecycle (before the row in the database is created, after the row is updated, …).

Defining Lifecycle Callbacks

When the behavior does not need any service and should be applied to only one kind of entity, define a callback in the entity class:

patch_file

  1. --- a/src/Entity/Comment.php
  2. +++ b/src/Entity/Comment.php
  3. @@ -7,6 +7,7 @@ use Doctrine\ORM\Mapping as ORM;
  4. /**
  5. * @ORM\Entity(repositoryClass=CommentRepository::class)
  6. + * @ORM\HasLifecycleCallbacks()
  7. */
  8. class Comment
  9. {
  10. @@ -106,6 +107,14 @@ class Comment
  11. return $this;
  12. }
  13. + /**
  14. + * @ORM\PrePersist
  15. + */
  16. + public function setCreatedAtValue()
  17. + {
  18. + $this->createdAt = new \DateTime();
  19. + }
  20. +
  21. public function getConference(): ?Conference
  22. {
  23. return $this->conference;

The @ORM\PrePersist event is triggered when the object is stored in the database for the very first time. When that happens, the setCreatedAtValue() method is called and the current date and time is used for the value of the createdAt property.

Adding Slugs to Conferences

The URLs for conferences are not meaningful: /conference/1. More importantly, they depend on an implementation detail (the primary key in the database is leaked).

What about using URLs like /conference/paris-2020 instead? That would look much better. paris-2020 is what we call the conference slug.

Add a new slug property for conferences (a not nullable string of 255 characters):

  1. $ symfony console make:entity Conference

Create a migration file to add the new column:

  1. $ symfony console make:migration

And execute that new migration:

  1. $ symfony console doctrine:migrations:migrate

Got an error? This is expected. Why? Because we asked for the slug to be not null but existing entries in the conference database will get a null value when the migration is ran. Let’s fix that by tweaking the migration:

patch_file

  1. --- a/migrations/Version00000000000000.php
  2. +++ b/migrations/Version00000000000000.php
  3. @@ -20,7 +20,9 @@ final class Version20200714152808 extends AbstractMigration
  4. public function up(Schema $schema) : void
  5. {
  6. // this up() migration is auto-generated, please modify it to your needs
  7. - $this->addSql('ALTER TABLE conference ADD slug VARCHAR(255) NOT NULL');
  8. + $this->addSql('ALTER TABLE conference ADD slug VARCHAR(255)');
  9. + $this->addSql("UPDATE conference SET slug=CONCAT(LOWER(city), '-', year)");
  10. + $this->addSql('ALTER TABLE conference ALTER COLUMN slug SET NOT NULL');
  11. }
  12. public function down(Schema $schema) : void

The trick here is to add the column and allow it to be null, then set the slug to a not null value, and finally, change the slug column to not allow null.

Note

For a real project, using CONCAT(LOWER(city), '-', year) might not be enough. In that case, we would need to use the “real” Slugger.

Migration should run fine now:

  1. $ symfony console doctrine:migrations:migrate

Because the application will soon use slugs to find each conference, let’s tweak the Conference entity to ensure that slug values are unique in the database:

patch_file

  1. --- a/src/Entity/Conference.php
  2. +++ b/src/Entity/Conference.php
  3. @@ -6,9 +6,11 @@ use App\Repository\ConferenceRepository;
  4. use Doctrine\Common\Collections\ArrayCollection;
  5. use Doctrine\Common\Collections\Collection;
  6. use Doctrine\ORM\Mapping as ORM;
  7. +use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
  8. /**
  9. * @ORM\Entity(repositoryClass=ConferenceRepository::class)
  10. + * @UniqueEntity("slug")
  11. */
  12. class Conference
  13. {
  14. @@ -40,7 +42,7 @@ class Conference
  15. private $comments;
  16. /**
  17. - * @ORM\Column(type="string", length=255)
  18. + * @ORM\Column(type="string", length=255, unique=true)
  19. */
  20. private $slug;

As we are using a validator to ensure the unique-ness of slugs, we need to add the Symfony Validator component:

  1. $ symfony composer req validator

As you might have guessed, we need to perform the migration dance:

  1. $ symfony console make:migration
  1. $ symfony console doctrine:migrations:migrate

Generating Slugs

Generating a slug that reads well in a URL (where anything besides ASCII characters should be encoded) is a challenging task, especially for languages other than English. How do you convert é to e for instance?

Instead of reinventing the wheel, let’s use the Symfony String component, which eases the manipulation of strings and provides a slugger:

  1. $ symfony composer req string

Add a computeSlug() method to the Conference class that computes the slug based on the conference data:

patch_file

  1. --- a/src/Entity/Conference.php
  2. +++ b/src/Entity/Conference.php
  3. @@ -7,6 +7,7 @@ use Doctrine\Common\Collections\ArrayCollection;
  4. use Doctrine\Common\Collections\Collection;
  5. use Doctrine\ORM\Mapping as ORM;
  6. use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
  7. +use Symfony\Component\String\Slugger\SluggerInterface;
  8. /**
  9. * @ORM\Entity(repositoryClass=ConferenceRepository::class)
  10. @@ -61,6 +62,13 @@ class Conference
  11. return $this->id;
  12. }
  13. + public function computeSlug(SluggerInterface $slugger)
  14. + {
  15. + if (!$this->slug || '-' === $this->slug) {
  16. + $this->slug = (string) $slugger->slug((string) $this)->lower();
  17. + }
  18. + }
  19. +
  20. public function getCity(): ?string
  21. {
  22. return $this->city;

The computeSlug() method only computes a slug when the current slug is empty or set to the special - value. Why do we need the - special value? Because when adding a conference in the backend, the slug is required. So, we need a non-empty value that tells the application that we want the slug to be automatically generated.

Defining a Complex Lifecycle Callback

As for the createdAt property, the slug one should be set automatically whenever the conference is updated by calling the computeSlug() method.

But as this method depends on a SluggerInterface implementation, we cannot add a prePersist event as before (we don’t have a way to inject the slugger).

Instead, create a Doctrine entity listener:

src/EntityListener/ConferenceEntityListener.php

  1. namespace App\EntityListener;
  2. use App\Entity\Conference;
  3. use Doctrine\ORM\Event\LifecycleEventArgs;
  4. use Symfony\Component\String\Slugger\SluggerInterface;
  5. class ConferenceEntityListener
  6. {
  7. private $slugger;
  8. public function __construct(SluggerInterface $slugger)
  9. {
  10. $this->slugger = $slugger;
  11. }
  12. public function prePersist(Conference $conference, LifecycleEventArgs $event)
  13. {
  14. $conference->computeSlug($this->slugger);
  15. }
  16. public function preUpdate(Conference $conference, LifecycleEventArgs $event)
  17. {
  18. $conference->computeSlug($this->slugger);
  19. }
  20. }

Note that the slug is updated when a new conference is created (prePersist()) and whenever it is updated (preUpdate()).

Configuring a Service in the Container

Up until now, we have not talked about one key component of Symfony, the dependency injection container. The container is responsible for managing services: creating them and injecting them whenever needed.

A service is a “global” object that provides features (e.g. a mailer, a logger, a slugger, etc.) unlike data objects (e.g. Doctrine entity instances).

You rarely interact with the container directly as it automatically injects service objects whenever you need them: the container injects the controller argument objects when you type-hint them for instance.

If you wondered how the event listener was registered in the previous step, you now have the answer: the container. When a class implements some specific interfaces, the container knows that the class needs to be registered in a certain way.

Unfortunately, automation is not provided for everything, especially for third-party packages. The entity listener that we just wrote is one such example; it cannot be managed by the Symfony service container automatically as it does not implement any interface and it does not extend a “well-know class”.

We need to partially declare the listener in the container. The dependency wiring can be omitted as it can still be guessed by the container, but we need to manually add some tags to register the listener with the Doctrine event dispatcher:

patch_file

  1. --- a/config/services.yaml
  2. +++ b/config/services.yaml
  3. @@ -29,3 +29,7 @@ services:
  4. # add more service definitions when explicit configuration is needed
  5. # please note that last definitions always *replace* previous ones
  6. + App\EntityListener\ConferenceEntityListener:
  7. + tags:
  8. + - { name: 'doctrine.orm.entity_listener', event: 'prePersist', entity: 'App\Entity\Conference'}
  9. + - { name: 'doctrine.orm.entity_listener', event: 'preUpdate', entity: 'App\Entity\Conference'}

Note

Don’t confuse Doctrine event listeners and Symfony ones. Even if they look very similar, they are not using the same infrastructure under the hood.

Using Slugs in the Application

Try adding more conferences in the backend and change the city or the year of an existing one; the slug won’t be updated except if you use the special - value.

The last change is to update the controllers and the templates to use the conference slug instead of the conference id for routes:

patch_file

  1. --- a/src/Controller/ConferenceController.php
  2. +++ b/src/Controller/ConferenceController.php
  3. @@ -28,7 +28,7 @@ class ConferenceController extends AbstractController
  4. ]));
  5. }
  6. - #[Route('/conference/{id}', name: 'conference')]
  7. + #[Route('/conference/{slug}', name: 'conference')]
  8. public function show(Request $request, Conference $conference, CommentRepository $commentRepository): Response
  9. {
  10. $offset = max(0, $request->query->getInt('offset', 0));
  11. --- a/templates/base.html.twig
  12. +++ b/templates/base.html.twig
  13. @@ -12,7 +12,7 @@
  14. <h1><a href="{{ path('homepage') }}">Guestbook</a></h1>
  15. <ul>
  16. {% for conference in conferences %}
  17. - <li><a href="{{ path('conference', { id: conference.id }) }}">{{ conference }}</a></li>
  18. + <li><a href="{{ path('conference', { slug: conference.slug }) }}">{{ conference }}</a></li>
  19. {% endfor %}
  20. </ul>
  21. <hr />
  22. --- a/templates/conference/index.html.twig
  23. +++ b/templates/conference/index.html.twig
  24. @@ -8,7 +8,7 @@
  25. {% for conference in conferences %}
  26. <h4>{{ conference }}</h4>
  27. <p>
  28. - <a href="{{ path('conference', { id: conference.id }) }}">View</a>
  29. + <a href="{{ path('conference', { slug: conference.slug }) }}">View</a>
  30. </p>
  31. {% endfor %}
  32. {% endblock %}
  33. --- a/templates/conference/show.html.twig
  34. +++ b/templates/conference/show.html.twig
  35. @@ -22,10 +22,10 @@
  36. {% endfor %}
  37. {% if previous >= 0 %}
  38. - <a href="{{ path('conference', { id: conference.id, offset: previous }) }}">Previous</a>
  39. + <a href="{{ path('conference', { slug: conference.slug, offset: previous }) }}">Previous</a>
  40. {% endif %}
  41. {% if next < comments|length %}
  42. - <a href="{{ path('conference', { id: conference.id, offset: next }) }}">Next</a>
  43. + <a href="{{ path('conference', { slug: conference.slug, offset: next }) }}">Next</a>
  44. {% endif %}
  45. {% else %}
  46. <div>No comments have been posted yet for this conference.</div>

Accessing conference pages should now be done via its slug:

Step 13: Managing the Lifecycle of Doctrine Objects - 图1

Going Further


This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.