Skip to content

Commit 26077b5

Browse files
committed
add description of doctrine event subscriber and hint on difference between symfony and doctrine event subscriber
1 parent 35d7bc6 commit 26077b5

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

components/event_dispatcher/introduction.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,8 @@ can be the way to go, especially for optional dependencies.
380380
.. index::
381381
single: Event Dispatcher; Event subscribers
382382

383+
.. _event_dispatcher-using-event-subscribers:
384+
383385
Using Event Subscribers
384386
~~~~~~~~~~~~~~~~~~~~~~~
385387

cookbook/doctrine/event_listeners_subscribers.rst

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,4 +152,56 @@ specific type of entity (e.g. a ``Product`` entity but not a ``BlogPost``
152152
entity), you should check for the class name of the entity in your method
153153
(as shown above).
154154

155+
Creating the Subscriber Class
156+
-----------------------------
157+
158+
A doctrine event subscriber must implement the ``Doctrine\Common\EventSubscriber``
159+
interface and an event method for each event it subscribes to.
160+
161+
162+
// src/Acme/SearchBundle/EventListener/SearchIndexerSubscriber.php
163+
namespace Acme\SearchBundle\EventListener;
164+
165+
use Doctrine\Common\EventSubscriber;
166+
use Doctrine\ORM\Event\LifecycleEventArgs;
167+
use Acme\StoreBundle\Entity\Product;
168+
169+
class SearchIndexerSubscriber implements EventSubscriber
170+
{
171+
public function getSubscribedEvents()
172+
{
173+
return array(
174+
'postPersist',
175+
'postUpdate',
176+
);
177+
}
178+
public function postUpdate(LifecycleEventArgs $args)
179+
{
180+
$this->index($args);
181+
}
182+
public function postPersist(LifecycleEventArgs $args)
183+
{
184+
$this->index($args);
185+
}
186+
public function index(LifecycleEventArgs $args)
187+
{
188+
$entity = $args->getEntity();
189+
$entityManager = $args->getEntityManager();
190+
191+
// perhaps you only want to act on some "Product" entity
192+
if ($entity instanceof Product) {
193+
// ... do something with the Product
194+
}
195+
}
196+
}
197+
198+
.. hint::
199+
200+
Doctrine event subscribers can not return a flexible array of methods to
201+
call for the events like the :ref:`Symfony event subscriber <event_dispatcher-using-event-subscribers>`
202+
can do. Doctrine event subscribers must return a simple array of the event
203+
names they subscribe to. Doctrine will then expect methods on the subscriber
204+
with the names of the subscribed events, just as when using an event listener.
205+
206+
155207
.. _`The Event System`: http://docs.doctrine-project.org/projects/doctrine-orm/en/2.1/reference/events.html

0 commit comments

Comments
 (0)