PHP code example of kelvinmo / f3-event-dispatcher

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

    

kelvinmo / f3-event-dispatcher example snippets


$listeners = \Listeners::instance();

// Object method
$listeners->on(FooEvent::class, 'Bar->listener');

// Static method
$listeners->on(FooEvent::class, 'Bar::listener');

// PHP callable
$listeners->on(FooEvent::class, [ $object, 'listener' ]);

// Closure
$listeners->on(FooEvent::class, function($event) {
    // listener
});

// Baz->listener is called first, then Bar->listener
$listeners->on(FooEvent::class, 'Bar->listener', 10);
$listeners->on(FooEvent::class, 'Baz->listener', 20);

class BarEvent implements GenericEventInterface {
    private $eventName;

    public function __construct($eventName) {
        $this->eventName = $eventName;
    }

    public function getEventName() {
        return $this->eventName;
    }
}

$listeners->on('foo', 'Baz->listener');
$event = new BarEvent('foo');

class TestListener {
    // Will be mapped to FooEvent (with namespace)
    public function onFooEvent(FooEvent $event) {
    }

    // Will be mapped to custom_event
    // (BarEvent must implement GenericEventInterface)
    public function onCustomEvent(BarEvent $event) {
    }
}

$listeners = \Listeners::instance();
$listeners->map(TestListener::class);

$dispatcher = \Events::instance();

use League\Event\PrioritizedListenerRegistry;

$listenerProvider = new PrioritizedListenerRegistry();
$dispatcher = \Events::instance($listenerProvider);

$dispatcher->dispatch(new FooEvent());