Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow declaring entity listeners without having to use explicit config #1343

Closed
nicolas-grekas opened this issue May 12, 2021 · 3 comments
Closed

Comments

@nicolas-grekas
Copy link
Member

Thanks to PHP 8 and autoconfiguration, we should be able to replace such configs by attributes:

    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'}

(example from the-fast-track)

$container->registerAttributeForAutoconfiguration() might help.

Help wanted!

@nicolas-grekas
Copy link
Member Author

nicolas-grekas commented May 12, 2021

Proposal:

#[AsEntityListener]
class ConferenceEntityListener
{
    private $slugger;

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

    // explicit style, all possible arguments listed
    #[OnEvent(event: Events::preUpdate, entity: Conference::class, lazy: true|false, entityManager: 'foo_em')]
    public function prePersist(Conference $conference, LifecycleEventArgs $event)
    {
        $conference->computeSlug($this->slugger);
    }

    // compact style: event/method and entity are inferred from the signature, no attribute is needed on the method
    public function preUpdate(Conference $conference, LifecycleEventArgs $event)
    {
        $conference->computeSlug($this->slugger);
    }
}

@ostrolucky
Copy link
Member

I don't think all of those tags are required. We do this in one of the projects

AppBundle\EventListener\AddToQueueListener:
        tags:
            - { name: doctrine.orm.entity_listener }
class AddToQueueListener
{
    public function postPersist(Queue $entity, LifecycleEventArgs $args): void
    {
        $job = new Job('everlution:queue:process', [$entity->getId()], true, QueueManager::POSTING_QUEUE);
        $job->setMaxRetries(1);
        $job->setMaxRuntime(30);
        $args->getEntityManager()->persist($job);
        $args->getEntityManager()->flush();
    }
}
/**
 * @ORM\Entity
 * @ORM\EntityListeners({AddToQueueListener::class})
 */
class Queue implements TimestampableInterface
{
}

@nicolas-grekas
Copy link
Member Author

Great! So we might only need #[AsEntityListener] to replace the explicit tag and the rest already exists!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants