PHP code example of slince / event-dispatcher

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

    

slince / event-dispatcher example snippets


$dispatcher = new Slince\EventDispatcher\Dispatcher();

use Slince\EventDispatcher\ListenerInterface;

class FooListener implements ListenerInterface
{
     public function handle(Event $event)
     {
         //do something
     }
}

$dispatcher->addListener('foo-event-name', new FooListener());

$dispatcher->addListener('foo-event-name', function(Event $event){
    //do something
});

use Slince\EventDispatcher\SubscriberInterface;

class FooSubscriber implements SubscriberInterface
{
     public static function getSubscribedEvents(Event $event)
     {
        return [
            'foo' => 'onFoo',
            'bar' => 'onBar'
        ];
     }
     
    public function onFoo(Event $event)
    {
      //do something
    }
    
    public function onBar(Event $event)
    {
       //do something
    }
}

$dispatcher->addSubscriber(new FooSubscriber());

$dispatcher->dispatch('foo-event-name');

$dispatcher->dispatch(new Event('foo-event-name'));

$dispatcher->addListener('foo-event-name', function(Event $event){
    $event->stopPropagation();
});

$emitter->addListener('foo-event-name', function ($event) {
    // This will not be triggered
});

$dispatcher->dispatch('foo-event-name');

 $event = new Event('foo-event-name');
 $dispatcher->dispatch($event);
 
 $event->isPropagationStopped();