PHP code example of ifcanduela / events

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

    

ifcanduela / events example snippets


class MyEventType
{
    public $someProperty;

    public function __construct(int $data)
    {
        $this->someProperty = $data;
    }
}

class MyEventEmitter
{
    use \ifcanduela\events\CanEmitEvents;

    public function createData()
    {
        $data = random_int();

        // using an object as event
        $this->emit(new MyEventType($data));

        // using a string as event name; the array will be sent to the listener
        $this->emit("data.created", ["data" => $data]);
    }
}

class MyEventListener
{
    public function __construct()
    {
        $this->listenTo(MyEventType::class, function ($event) {
            echo $event->someProperty;
        });

        $this->listenTo("data.created", function ($payload) {
            echo $payload["data"];
        });

        $this->listenTo("data.created", [$this, "eventHandler"]);
    }

    public function eventHandler($payload)
    {
        echo $payload["data"];
    }
}

EventManager::register("event.name", function ($payload) {
    assert($payload["a"] === 1);
    assert($payload["b"] === 2);
});

EventManager::trigger("event.name", ["a" => 1, "b" => 2]);