@@ -134,6 +134,54 @@ listener class:
134134 internal Symfony listeners usually range from ``-256 `` to ``256 `` but your
135135 own listeners can use any positive or negative integer.
136136
137+ Defining Event Listeners with PHP Attributes
138+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
139+
140+ An alternative way to define an event listener is to use the
141+ :class: `Symfony\\ Component\\ EventDispatcher\\ Attribute\\ AsEventListener `
142+ PHP attribute. This allows to configure the listener inside its class, without
143+ having to add any configuration in external files::
144+
145+ namespace App\EventListener;
146+
147+ use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
148+
149+ #[AsEventListener]
150+ final class MyListener
151+ {
152+ public function __invoke(CustomEvent $event): void
153+ {
154+ // ...
155+ }
156+ }
157+
158+ You can add multiple ``#[AsEventListener()] `` attributes to configure different methods::
159+
160+ namespace App\EventListener;
161+
162+ use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
163+
164+ #[AsEventListener(event: CustomEvent::class, method: 'onCustomEvent')]
165+ #[AsEventListener(event: 'foo', priority: 42)]
166+ #[AsEventListener(event: 'bar', method: 'onBarEvent')]
167+ final class MyMultiListener
168+ {
169+ public function onCustomEvent(CustomEvent $event): void
170+ {
171+ // ...
172+ }
173+
174+ public function onFoo(): void
175+ {
176+ // ...
177+ }
178+
179+ public function onBarEvent(): void
180+ {
181+ // ...
182+ }
183+ }
184+
137185.. _events-subscriber :
138186
139187Creating an Event Subscriber
0 commit comments