How to use Doctrine Entity Listener with Symfony 2

2019-01-15 04:57发布

问题:

I want to use Doctrine Entity Listener with Symfony 2.4.

I've created a class:

<?php

namespace MyBundle\Listener\Entity;

use Doctrine\ORM\Event\LifecycleEventArgs;
use MyBundle\Entity\User;

class UserListener
{
    public function postPersist(User $user, LifecycleEventArgs $event)
    {
    }
}

I've added mapping information:

<?xml version="1.0" encoding="UTF-8" ?>
<doctrine-mapping>
    <entity name="MyBundle\Entity\User">

        ...

        <entity-listeners>
            <entity-listener class="MyBundle\Listener\Entity\UserListener" />
        </entity-listeners>

    </entity>
</doctrine-mapping>

It's working OK. But how do I pass some services to this class? I want it to be integrated with the Symfony's service container and provided services.

回答1:

To register a specific entity listener instance in symfony please follow this steps:

1) Update DoctrineBundle in your composer.json to the version 1.3 (since it's not yet stable):

{
    "require": {
        "doctrine/doctrine-bundle": "1.3.x-dev",
    }
}

2) Register your own service with tag name "doctrine.orm.entity_listener":

my.listener:
    class: MyBundle\Listener\Entity\UserListener
    arguments: [ ... ]
    tags:
        - { name: doctrine.orm.entity_listener }

See the Symfony docs on Entity Listeners.