The laminas/laminas-eventmanager composer package serves as a tool for triggering and listening to events within your PHP application. It offers a simplified solution to implementing various design patterns such as the subject/observer pattern, Aspect-Oriented designs and event-driven architectures. It offers a robust architecture that facilitates the attachment and detachment of listeners to named events, either on a per-instance basis or through shared collections. It also offers the ability to trigger events and interrupt listener execution.
To use laminas/laminas-eventmanager in your PHP project, you need to install it via composer using the command composer require laminas/laminas-eventmanager
. After installation, you can create an instance of the EventManager, register events, and then attach and trigger them as needed in your code. Here's a basic code usage example:
use Laminas\EventManager\EventManager;
$events = new EventManager();
// Attach to an event
$events->attach('do', function ($event) {
$name = $event->getName();
$params = $event->getParams();
echo sprintf(
'Handled event "%s", with parameters %s',
$name,
json_encode($params)
);
});
// Trigger the event
$events->trigger('do', null, ['param1' => 'value1']);
In the above code, an event named 'do' is created and a closure is attached as the listener. The listener simply outputs a message indicating the event name and parameters. Afterwards, the event is triggered with 'param1' set to 'value1'.
The detailed documentation for laminas/laminas-eventmanager can be found on the Laminas Project's official website at https://docs.laminas.dev/laminas-eventmanager/. Here you'll find comprehensive guides and explanations on how to effectively leverage the capabilities this tool provides. If you are migrating from version 2 to version 3 of laminas-eventmanager, there is specific migration documentation available to assist with the transition.