You are viewing the website for BitFrame v1. BitFrame v2.0 was released on 11-May-2020 — new documentation and website will be available soon!


Learn how to work with events in BitFrame using the event manager

Event Manager

Create An Event:

You can create a custom event simply by creating a new instance of \BitFrame\EventManager\Event and triggering it:

use \BitFrame\EventManager\Event;

/* create new event  */
$event = new Event('name', 'target', ['test' => 'hello world']);

Trigger Event

An event can be triggered by calling the trigger method on the \BitFrame\EventManager\EventManager object instance. We can get the default event manager by calling the static method ApplicationFactory::createEventManager(). This would by default create an instance of \BitFrame\EventManager\EventManager based on the \BitFrame\Factory\EventManagerFactory, for example:

use \BitFrame\Factory\ApplicationFactory;

$eventManager = ApplicationFactory::createEventManager();

/* trigger event  */
$eventManager->trigger($event, null, [
    'test' => 'will have this value', 
    'new_param' => 'hello world'

You may have noticed we've specified the target as null. You could, however, make the target any object or string as well depending on what your event intends to do and to what object it intends to do it to.

In the third (optional) argument to the trigger() method we can supply params to the event. You may have noticed that we specified some params when we created the event earlier. These params, in case of similar keys, are overwritten by the ones we supply via the trigger() method.

The next step naturally is to add event listeners which are invoked when the events are triggered.

Attach Event Listener

We can listen to an event by attaching an event listener to the event name. This can be done via the event manager, for example:

/* attach event  */
$eventManager->attach('name', function($event) {
    echo $event->getParam('test'); // outputs: 'will have this value'
    echo $event->getParam('new_param'); // outputs: 'hello world'

Now the callback you attached to the event would run when the event is triggered (via the trigger() method).

Detach Event Listener

Similar to the attach() method, we could remove an event listener by using the detach() method:

/* detach event  */
$eventManager->detach('name', function($event) {
   // do something...

We could also use the clearListeners() method to remove all listeners:

/* clear all listeners  */

// or to remove all listeners for a specific event:
$eventManager->clearListeners(/* $eventName */);

Get All Event's Listeners:

You could retrieve all listeners attached to a specific event name like so:

/* get all event's listeners  */
$eventManager->getListeners(/* $eventName */);


Let us know if you have something to say or add