Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 206c311

Browse files
committed
minor #17030 [EventDispatcher] Document the #AsEventListener attribute (94noni)
This PR was submitted for the 6.0 branch but it was merged into the 5.4 branch instead. Discussion ---------- [EventDispatcher] Document the #AsEventListener attribute Document the AsEventListener attribute Ref symfony/symfony#47015 (did not found any doc thus opened an issue at first) For the code example, I've taken inspiration on the related PR: - symfony/symfony@2ab3caf#diff-57b112e725705bbbf01380b0d11c9a8fe16ea69d85d1d3e618eceeb8b58094ce - symfony/symfony@2ab3caf#diff-73a6a14d3288b358a21c0f47ecc1ec78c05e933b66e9a647e5013b2cab002b89 Commits ------- ff5032d Update event_dispatcher.rst
2 parents 8e943c7 + ff5032d commit 206c311

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

components/event_dispatcher.rst

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,49 @@ Take the following example of a subscriber that subscribes to the
402402
}
403403
}
404404

405+
You can also leverage the :class:`Symfony\\Component\\EventDispatcher\\Attribute\\AsEventListener`
406+
attribute to configure your class as a listener on event::
407+
408+
namespace App\EventListener;
409+
410+
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
411+
412+
#[AsEventListener]
413+
final class MyListener
414+
{
415+
public function __invoke(CustomEvent $event): void
416+
{
417+
// ...
418+
}
419+
}
420+
421+
or any of a class methods like so::
422+
423+
namespace App\EventListener;
424+
425+
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
426+
427+
#[AsEventListener(event: CustomEvent::class, method: 'onCustomEvent')]
428+
#[AsEventListener(event: 'foo', priority: 42)]
429+
#[AsEventListener(event: 'bar', method: 'onBarEvent')]
430+
final class MyMultiListener
431+
{
432+
public function onCustomEvent(CustomEvent $event): void
433+
{
434+
// ...
435+
}
436+
437+
public function onFoo(): void
438+
{
439+
// ...
440+
}
441+
442+
public function onBarEvent(): void
443+
{
444+
// ...
445+
}
446+
}
447+
405448
This is very similar to a listener class, except that the class itself can
406449
tell the dispatcher which events it should listen to. To register a subscriber
407450
with the dispatcher, use the

0 commit comments

Comments
 (0)