DEV Community

Aymeric Ratinaud
Aymeric Ratinaud

Posted on • Updated on

Do you know DoctrineListener?

Imagine you had to monitor an entity to log when it was created or updated

Create a Note entity

<?php

namespace App\Entity;

use App\Repository\NoteRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: NoteRepository::class)]
class Note
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(type: Types::TEXT)]
    private ?string $content = null;

    #[ORM\Column(length: 255)]
    private ?string $log = null;

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

    public function getContent(): ?string
    {
        return $this->content;
    }

    public function setContent(string $content): static
    {
        $this->content = $content;

        return $this;
    }

    public function getLog(): ?string
    {
        return $this->log;
    }

    public function setLog(string $log): static
    {
        $this->log = $log;

        return $this;
    }
}
Enter fullscreen mode Exit fullscreen mode

Then you can create a DoctrineListener to log when its created (persist) or updated

<?php

namespace App\DoctrineListener;

use App\Entity\Conference;
use App\Entity\Note;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;


#[AsEntityListener(event: Events::prePersist, entity: Note::class)]
#[AsEntityListener(event: Events::preUpdate, entity: Note::class)]
class NoteEntityListener
{
    public function prePersist(Note $note, LifecycleEventArgs $event)
    {
        $note->setLog('This is from prePersist');
    }

    public function preUpdate(Note $note, LifecycleEventArgs $event)
    {
        $note->setLog('This is from preUpdate');
    }
}
Enter fullscreen mode Exit fullscreen mode

That's all !
The doctrinelistener will be called at each persist or update.

Here is the complete list of events:

  • preRemove
  • postRemove
  • prePersist
  • postPersist
  • preUpdate
  • postUpdate
  • postLoad
  • preFlush
  • onFlush
  • postFlush
  • onClear

You have a demo at this address https://github.com/aratinau/api-platform-doctrine

Top comments (2)

Collapse
 
shagshag profile image
Georges Cubas

Thanks, I didn't know.

Is the SluggerInterface mandatory?

Collapse
 
aratinau profile image
Aymeric Ratinaud

No, you're right, I take it off