PHP code example of atphp / event

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

    

atphp / event example snippets



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();


$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!"]