@@ -235,8 +235,9 @@ Doctrine Entity Listeners
235
235
236
236
Entity listeners are defined as PHP classes that listen to a single Doctrine
237
237
event on a single entity class. For example, suppose that you want to send some
238
- notifications whenever a ``User `` entity is modified in the database. To do so,
239
- define a listener for the ``postUpdate `` Doctrine event::
238
+ notifications whenever a ``User `` entity is modified in the database.
239
+
240
+ First, define a PHP class that handles the ``postUpdate `` Doctrine event::
240
241
241
242
// src/EventListener/UserChangedNotifier.php
242
243
namespace App\EventListener;
@@ -254,9 +255,27 @@ define a listener for the ``postUpdate`` Doctrine event::
254
255
}
255
256
}
256
257
257
- The next step is to enable the Doctrine listener in the Symfony application by
258
- creating a new service for it and :doc: `tagging it </service_container/tags >`
259
- with the ``doctrine.orm.entity_listener `` tag:
258
+ Then, add the ``#[AsDoctrineListener] `` attribute to the class to enable it as
259
+ a Doctrine entity listener in your application:
260
+
261
+ .. code-block :: php
262
+
263
+ // src/EventListener/UserChangedNotifier.php
264
+ namespace App\EventListener;
265
+
266
+ // ...
267
+ use App\Entity\User;
268
+ use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
269
+
270
+ #[AsDoctrineListener(event: 'postUpdate', method: 'postUpdate', entity: User::class)]
271
+ class UserChangedNotifier
272
+ {
273
+ // ...
274
+ }
275
+
276
+ That's it. Alternatively, if you prefer to not use PHP attributes, you must
277
+ configure a service for the entity listener and :doc: `tag it </service_container/tags >`
278
+ with the ``doctrine.orm.entity_listener `` tag as follows:
260
279
261
280
.. configuration-block ::
262
281
0 commit comments