Documentation
Middleware Events
Activating Event Middlewares
Cygnite provides you simple way of attaching number of events in your application. Events will trigger as soon as you activate it in /src/Application/Configs/application.php file. You just need to configure 'activate.event.middleware' as true. Also you have to register events by specifying in the listen property of src/Apps/Middleware/Events/Event class. All registered events will trigger at runtime. Wondering how it works? Below example.
namespace Apps\Middleware\Events;
use Cygnite\Foundation\Application;
use Cygnite\Base\EventHandler\Event as EventListener;
class Event extends EventListener
{
// Specify all event stack
protected $listen = [
'event.api.run' => '\Apps\Resources\Extensions\Api@run',
];
/**
* Activate application event, return true/false
*
* @return bool
*/
public function isAppEventEnabled()
{
return true;
}
/**
* This events will get executed before and after
* Application::bootApplication() method
*
* @return array
*/
public function registerAppEvents()
{
return [
'beforeBootingApplication' => '\Apps\Resources\Extensions\Foo@configureGatewayes',
'afterBootingApplication' => '\Apps\Resources\Extensions\Foo@payment'
];
}
/**
* Fire Registered events or set into container object
* @param $container
*/
public function register($container)
{
parent::boot($this);
$container['event.api.run'] = $this->fire('event.api.run');
}
}
The name specified after the @ symbol is method name in the specified class. You can attach event for any method. In the above example we have attached event for the run() method of Apps\Resources\Extensions\Api class, while firing the stored event it will also trigger beforeRun() and afterRun() methods. You may store the event into container so you can trigger when ever you want, below Example.
$app['event.api.run']; // will call events registered on the method
Similarly when you change $activateAppEvent property as true it will trigger methods registered before and after booting the application.
Attaching an Event
$event = new \Cygnite\Base\EventHandler\Event();
$event->attach('beforeSave', 'calculateAge');
or
$event->attach('afterValidation', '\Apps\Resources\Extensions\Api@calculateTax');
or
$event->attach('event-name', function ()
{
echo "Hellow Here.";
});
function calculateAge()
{
echo "Calculate Age";
}
Triggering An Event
For Example :
$event->trigger('event-name');
or
$event->trigger('beforeSave'); //Prints Calculate Age
or
//path : Apps/Resources/Extensions/Api.php
class Api
{
public function calculateTax()
{
echo "Calculate Tax";
}
}
$event->('afterValidation');
Flush Event
You can specify event name which you want to de-attach. Some time you may wish to de-attach all event, use flush() method in such case.
For Example :
$event->flush('event-name'); // flush particular event.
or
$event->flush(); //will de-attach all events