1. Go to this page and download the library: Download koriit/eventdispatcher library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
koriit / eventdispatcher example snippets
// configure and build your container
$dispatcher = new EventDispatcher($container);
$listener = function (LoggerInterface $logger, Request $request) {
$logger->info($request->getMethod().' '.$request->getPathInfo());
};
$dispatcher->addListener("init", $listener, 10);
$dispatcher->dispatch("init");
// MyClass.php
class MyClass
{
public function logRequest(LoggerInterface $logger, Request $request)
{
$logger->info($request->getMethod().' '.$request->getPathInfo());
}
}
// configure and build your container
$dispatcher = $container->get(EventDispatcherInterface::class);
$dispatcher->addListener(ApplicationLifecycle::INITIALIZING, [MyClass::class, 'logRequest'], 10);
$dispatcher->dispatch(ApplicationLifecycle::INITIALIZING);
// MyInterface.php
interface MyInterface
{
public function logRequest(LoggerInterface $logger, Request $request);
}
// MyClass.php
class MyClass implements MyInterface
{
public function logRequest(LoggerInterface $logger, Request $request)
{
$logger->info($request->getMethod().' '.$request->getPathInfo());
}
}
// configure and build your container
$dispatcher = $container->get(EventDispatcherInterface::class);
$dispatcher->addListener(InitializationEvent::class, [MyInterface::class, 'logRequest'], 10);
$dispatcher->dispatch(InitializationEvent::class, ["event" => new InitializationEvent()]);
interface EventDispatcherInterface
{
// ..
/**
* Subscribes a listener to given event with specific priority.
*
* Listener must be invokable by PHP-DI.
*
* The higher the priority value the later the listener will be called.
* Listeners with the same priority will be called in the order they have been subscribed.
*
* @param mixed $eventName
* @param mixed $listener
* @param int $priority
*/
public function addListener($eventName, $listener, $priority = 0);
// ...
}
interface EventDispatcherInterface
{
// ..
/**
* Subscribes listeners in bulk.
*
* Listeners array is a simple structure of 3 levels:
* - At first level it is associative array where keys are names of registered events
* - At second level it is indexed array where keys are priority values
* - At third level it is simple list containing listeners subscribed to given event with given priority
*
* @param array $listeners
*
* @return void
*/
public function addListeners($listeners);
// ...
}