sajad torkamani

You have two options for defining callbacks for your Doctrine entities.

1. Define callback in the entity class

If your callback doesn’t require any other services and only applies to a single entity, you can define it directly in the entity class:

#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\HasLifecycleCallbacks]
class User
{
  // All the other properties and methods...

  #[ORM\PrePersist]
  public function setCreatedAtValue()
  {
    $this->createdAt = new \DateTimeImmutable();
  }
}

Remember to add the #[ORM\HasLifecycleCallbacks] annotation to the entity class.

2. Create a Doctrine entity listener

For more complex listeners where you need to use other services, you can create a dedicated listener class (e.g., src/EntityListener/ConferenceEntityListener.php):

<?php

namespace App\EntityListener;

use App\Entity\Conference;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\String\Slugger\SluggerInterface;

class ConferenceEntityListener
{
    private SluggerInterface $slugger;

    public function __construct(SluggerInterface $slugger)
    {
        $this->slugger = $slugger;
    }

    public function prePersist(Conference $conference, LifecycleEventArgs $event)
    {
        $conference->computeSlug($this->slugger);
    }

    public function preUpdate(Conference $conference, LifecycleEventArgs $event)
    {
        $conference->computeSlug($this->slugger);
    }
}

You’ll then need to register the entity listener with the Doctrine event dispatcher by adding the following to config/services.yaml:

# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous on  
App\EntityListener\ConferenceEntityListener:
  tags:
    - { name: 'doctrine.orm.entity_listener', event: 'prePersist', entity: 'App\Entity\Conference' }
    - { name: 'doctrine.orm.entity_listener', event: 'preUpdate', entity: 'App\Entity\Conference' }

Sources

Tagged: Symfony