Using Doctrine Entity Listeners in Symfony2

June 14, 2016 | No Comments | Programming | doctrine listener Symfony2

Since doctrine 2.4 we can use Entity Listeners to perform operations before/after saving entity in database.  How to use entity listeners in Symfony2 ?  For example we need to log our entity on some condition.

Let’s create our PostListener class:

<?php
 
// /src/ContentBundle/EntityListener/PostListener.php
 
namespace ContentBundle\EntityListener;
 
use ContentBundle\Entity\Post;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Psr\Log\LoggerInterface;
 
class PostListener
{
    /**
     * @var LoggerInterface
     */
    private $logger;
 
    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
 
    public function prePersist(Post $post, LifecycleEventArgs $event)
    {
        if($post->getTitle() == '...'){
            $this->logger->info(sprintf('Strange post #%d',$post->getId()));
        }
    }
}

Now add information about our listener in entity mapping. Example for xml:

<!-- /src/ContentBundle/Resources/config/doctrine/Post.orm.xml -->
<entity name="ContentBundle\Entity\Post" table="post" >
    <entity-listeners>
        <entity-listener class="ContentBundle\EntityListener\PostListener">
            <lifecycle-callback type="prePersist" method="prePersist"/>
        </entity-listener>
    </entity-listeners>
    <!-- Rest mapping -->
</entity>

Or in annotations:

/**
 * @ORM\Entity
 * @ORM\EntityListeners({"ContentBundle\EntityListener\PostListener"})
 */

Last, add service in our configuration:

#/src/ContentBundle/Resources/config/services.yml
content.post.entity_listener:
    class: ContentBundle\EntityListener\PostListener
    arguments: [@logger]
    tags:
        - { name: doctrine.orm.entity_listener }

But you should use entity listeners carefully because complex logic inside can cause unpredictable errors and break data.


About the Author / Artem Zhuravlev

Artem Zhuravlev. Web developer. Blog writer.

Need help with your website ? Contact with me by email infzanoza@gmail.com for services of experienced web developer.

Follow @infernosquad

LEAVE A COMMENT