atphp/event

Wrapper for Symfony EventDispatcher component to provide more functionality.

v0.1.4 2014-09-09 07:12 UTC

This package is auto-updated.

Last update: 2024-12-12 20:32:22 UTC


README

Wrapper for Symfony Event Dispatcher to provide more functionality.

<?php
use Symfony\Component\EventDispatcher\Event;
use AndTruong\Common\EventAware;

class MyClass extends EventAware
{

    public function myEventAwareMethod()
    {
        $this->dispatch('my.event.before');
        $event = new Event();
        $this->dispatch('my.event.after', $event);

        // or simpler
        $this->trigger('my.other.event', $this, ['param 1', 'param 2']);
    }

}

// Class usage
$myobj = new MyClass();
$myobj->getDispatcher()->addListener('my.event.before', function(\AndyTruong\Common\Event $e) {
    $e->getTarget(); // instance of MyClass
    $e->getParams(); // ['param 1', 'param 2']
});
$myobj->myEventAwareMethod();

Result collecting

In real projects, we often collect results from external code. It can be done easily like this:

<?php
$myobj = new MyClass();
$myobj->getDispatcher()->addListener('my.results.collecting.event', function(\AndyTruong\Common\Event $e) {
    $e->addResult("Hello there!");
});
$myobj->collectResults('my.results.collecting.event'); // ["Hello there!"]

// to validate input
$myobj->collectResults('my.results.collecting.event', null, null, [
    function($input) {
        if (!is_string($input)) { throw new \Exception('Input must be string!'); }
    }
]); // ["Hello there!"]