Skip to content

Mention lazy loading for Doctrine event listeners #8080

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

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions doctrine/event_listeners_subscribers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -214,5 +214,58 @@ interface and have an event method for each event it subscribes to::

For a full reference, see chapter `The Event System`_ in the Doctrine documentation.

Lazy loading for Event Listeners
--------------------------------

One subtle difference between listeners and subscribers is that Symfony can load
entity listeners lazily. This means that your listener class will only be fetched
from the service container (and thus be instantiated) once the event it is linked
to actually fires.

Lazy loading might give you a slight performance improvement when your listener
runs for events that rarely fire. Also, it can help you when you run into
*circular dependency issues* that may occur when your listener service in turn
depends on the DBAL connection.

To mark a listener service as lazily loaded, just add the ``lazy`` attribute
to the tag like so:

.. configuration-block::

.. code-block:: yaml

services:
my.listener:
class: AppBundle\EventListener\SearchIndexer
tags:
- { name: doctrine.event_listener, event: postPersist, lazy: true }

.. code-block:: xml

<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:doctrine="http://symfony.com/schema/dic/doctrine">

<services>
<service id="my.listener" class="AppBundle\EventListener\SearchIndexer">
<tag name="doctrine.event_listener" event="postPersist" lazy="true" />
</service>
</services>
</container>

.. code-block:: php

use AppBundle\EventListener\SearchIndexer;

$container
->register('my.listener', SearchIndexer::class)
->addTag('doctrine.event_listener', array('event' => 'postPersist', 'lazy' => 'true'))
;

.. note::

  Marking an event listener as ``lazy`` has nothing to do with lazy service
definitions which are described :doc:`in their own section </service_container/lazy_services>`

.. _`The Event System`: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html
.. _`the Doctrine Documentation`: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#entity-listeners