The Generic Event Object
Warning: You are browsing the documentation for Symfony 3.x, which is no longer maintained.
Read the updated version of this page for Symfony 7.1 (the current stable version).
The base Event class provided by the EventDispatcher component is deliberately sparse to allow the creation of API specific event objects by inheritance using OOP. This allows for elegant and readable code in complex applications.
The GenericEvent is available for convenience for those who wish to use just one event object throughout their application. It is suitable for most purposes straight out of the box, because it follows the standard observer pattern where the event object encapsulates an event 'subject', but has the addition of optional extra arguments.
GenericEvent has a simple API in addition to the base class Event
- __construct(): Constructor takes the event subject and any arguments;
- getSubject(): Get the subject;
- setArgument(): Sets an argument by key;
- setArguments(): Sets arguments array;
- getArgument(): Gets an argument by key;
- getArguments(): Getter for all arguments;
- hasArgument(): Returns true if the argument key exists;
The GenericEvent
also implements ArrayAccess on the event
arguments which makes it very convenient to pass extra arguments regarding
the event subject.
The following examples show use-cases to give a general idea of the flexibility. The examples assume event listeners have been added to the dispatcher.
Simply passing a subject:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
use Symfony\Component\EventDispatcher\GenericEvent;
$event = new GenericEvent($subject);
$dispatcher->dispatch('foo', $event);
class FooListener
{
public function handler(GenericEvent $event)
{
if ($event->getSubject() instanceof Foo) {
// ...
}
}
}
Passing and processing arguments using the ArrayAccess API to access the event arguments:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
use Symfony\Component\EventDispatcher\GenericEvent;
$event = new GenericEvent(
$subject,
['type' => 'foo', 'counter' => 0]
);
$dispatcher->dispatch('foo', $event);
class FooListener
{
public function handler(GenericEvent $event)
{
if (isset($event['type']) && $event['type'] === 'foo') {
// ... do something
}
$event['counter']++;
}
}
Filtering data:
1 2 3 4 5 6 7 8 9 10 11 12
use Symfony\Component\EventDispatcher\GenericEvent;
$event = new GenericEvent($subject, ['data' => 'Foo']);
$dispatcher->dispatch('foo', $event);
class FooListener
{
public function filter(GenericEvent $event)
{
$event['data'] = strtolower($event['data']);
}
}