getting started  »  events

Events

The event manager provides a way to hook specific event listeners and functionality into certain points in an application's life-cycle. You can create an event manager object and attach, detach or trigger event listeners. You can pass callable strings or already instantiated instances of objects, although the latter could be potentially less efficient.

$events = new Pop\Event\Manager();

$events->on('foo', 'MyApp\Event->bootstrap');
$events->on('bar', 'MyApp\Event::log');

$events->trigger('foo');

Similar to the services syntax, the valid callable strings for events are as follows:

  • 'someFunction'
  • 'SomeClass'
  • 'SomeClass->foo'
  • 'SomeClass::bar'

With events, you can also inject parameters into them as they are called, so that they may have access to any required elements or values. For example, perhaps you need an event to have access to elements and values from your main application object:

$events->trigger('foo', ['application' => $application]);

In the above example, any event listeners triggered by foo will get the application object injected into them so that the event called can utilize that object and retrieve data from it.

To detach an event listener, you call the off method:

$events->off('foo', 'MyApp\Event::someEvent');

Priority

Event listeners attached to the same event handler can be assigned a priority value to determine the order in which they fire. The higher the priority value, the earlier the event listener will fire.

$events->on('foo', 'MyApp\Event->bootstrap', 100);
$events->on('foo', 'MyApp\Event::log', 10);

Application Events

Within the context of a Pop application object, an event manager object is created by default or one can be injected. The default hook points within a Pop application object are:

  • app.init
  • app.route.pre
  • app.dispatch.pre
  • app.dispatch.post
  • app.error

This conveniently wires together various common points in the application's life-cycle where one may need to fire off an event of some kind. You can build upon these event hook points, creating your own that are specific to your application. For example, perhaps you require an event hook point right before a controller in your application sends a response. You could create an event hook point in your application like this:

$application->on('app.send.pre', 'MyApp\Event::logResponse');

And then in your controller method, right before you send then response, you would trigger that event:

class MyApp\Controller\IndexController extends \Pop\Controller\AbstractController
{
    public function index()
    {
        $this->application->trigger->('app.send.pre', ['controller' => $this]);
        echo 'Home Page';
    }
}

The above example injects the controller object into the event listener in case the event called requires interaction with the controller or any of its properties.