Reputation: 46208
I've never done anything event-driven in PHP, only Node.js, so I'm trying to understand how event dispatching systems work in PHP (such as Laravel events, CakePHP events and Symfony event dispatcher).
This example is in the Laravel docs:
protected $listen = [
'App\Events\OrderShipped' => [
'App\Listeners\SendShipmentNotification',
],
];
Since the lifetime of a PHP script running on Apache is basically the lifetime of the request, does this mean all the event listeners are instantiated with each request?
So if I have 120 listeners in my application (i.e. listed in this $listen
property), are all 120 of them going to be instantiated every time a page is visited? Or do the listener objects only get instantiated when the appropriate events are dispatched?
It seems quite inefficient for the listeners to be instantiated with each request when in the entire duration of the request there might not even be a single event fired.
Is this something that I should even be concerned about?
Upvotes: 3
Views: 836
Reputation: 2877
How an Event Listener system works.
In simplest terms it's just an array of text objects.
So in symfony you might do something like this
$eventManager->dispatch('my_cool_event_name', $eventPayload);
This will then look for anything that is listening for the event my_cool_event_name
by just doing an array look up
$events = [
'my_cool_event_name' => [
'events\notifyController::email',
'events\notifyController::text',
'events\notifyController::tweet',
],
'another_event' => [
]
];
So from the array example above it found 3 events listening on my_cool_event_name
, it'll then instansiate events\notifyController
and run the methods passing through the $eventPayload
to each event.
If you never dispatched my_cool_event_name
during execution then nothing gets instansiated
Upvotes: 5