PHP code example of gandung / event-dispatcher

1. Go to this page and download the library: Download gandung/event-dispatcher 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/ */

    

gandung / event-dispatcher example snippets


use Gandung\EventDispatcher\EventDispatcher;
use Gandung\EventDispatcher\EventContainer;

$dispatcher = new EventDispatcher(new EventContainer);

use Gandung\EventDispatcher\EventDispatcherFactory;

$factory = new EventDispatcherFactory;
$dispatcher = $factory->getDispatcher();

use Gandung\EventDispatcher\EventDispatcherFactory;

$factory = new EventDispatcherFactory;
$dispatcher = $factory->getDispatcher();
$listener = function() {
	echo "i'am a closure based listener.\n";
};

$dispatcher->attachListener('event.simple.closure', $listener, 20);
$dispatcher->dispatch('event.simple.closure');

use Gandung\EventDispatcher\EventDispatcherFactory;

class Foo
{
	public function dummyResolver()
	{
		echo sprintf("Inside {%s}@{%s}", \spl_object_hash($this), __METHOD__);
	}
}

$foo = new Foo();
$factory = new EventDispatcherFactory;
$dispatcher = $factory->getDispatcher();
$dispatcher->attachListener('event.simple.object', [$foo, 'dummyResolver'], 20);
$dispatcher->dispatch('event.simple.object');

use Gandung\EventDispatcher\EventDispatcherFactory;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class FooSubscriber implements EventSubscriberInterface
{
	public static function getSubscribedEvents()
	{
		return [
			'event.simple.prioritized' => [
				['dummyResolver1', 20],
				['dummyResolver2', 10],
				['dummyResolver3', -90]
			],
			'event.simple.unprioritized' => [
				'unprioritizedResolver'
			],
			'event.simple.single' => 'singleResolver'
		];
	}

	public function dummyResolver1()
	{
		echo sprintf("{%s@%s}\n", \spl_object_hash($this), __METHOD__);
	}

	public function dummyResolver2()
	{
		echo sprintf("{%s@%s}\n", \spl_object_hash($this), __METHOD__);
	}

	public function dummyResolver3()
	{
		echo sprintf("{%s@%s}\n", \spl_object_hash($this), __METHOD__);
	}

	public function unprioritizedResolver()
	{
		echo sprintf("{%s@%s}\n", \spl_object_hash($this), __METHOD__);
	}

	public function singleResolver()
	{
		echo sprintf("{%s@%s}\n", \spl_object_hash($this), __METHOD__);
	}
}

$subscriber = new FooSubscriber;
$factory = new EventDispatcherFactory();
$dispatcher->attachSubscriber($subscriber);
$dispatcher->dispatch('event.simple.prioritized');
$dispatcher->dispatch('event.simple.unprioritized');
$dispatcher->dispatch('event.simple.single');