Custom event

Creating and dispatching custom events

This library is abandoned. Please consider using a different library.

If an event must carry additional data, or must have a custom behavior, you should extend the Opis\Events\Event class to add the functionality.

The next example describes a custom event which can hold some arbitrary data.

use Opis\Events\Event;

class DataEvent extends Event 
{
    protected $data;
    
    public function __construct(string $name, $data, bool $cancelable = false) 
    {
        $this->data = $data;
        parent::construct($name, $cancellable);
    }
    
    public function data()
    {
        return $this->data;
    }
}

Custom events can be fired only by using the dispatch method of the event dispatcher object.

use Opis\Events\EventDispatcher;

$dispatcher = new EventDispatcher();

$dispatcher->handle('data.print', function (DataEvent $event) {
    print $event->data();
});

$event = new DataEvent("data.print", "some text");

$dispatcher->dispatch($event);

//> some text