PHP code example of mario-legenda / php-event-emitter

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

    

mario-legenda / php-event-emitter example snippets


class Task extends EventEmitter
{
    public function __construct()
    {
        parent::__construct(); // don't forget to call the parent Event Emitter constructor

        $this->emit('classConstructed');
    }

    public function runTask(): ExtendedTask
    {
        $this->emit('preRunEvent');
        
        // some task specific code

        $this->emit('postRunEvent');

        $this->emit('taskFinished');

        return $this;
    }
}

$task = new Task();

$task
    ->runTask()
    ->on('classConstructed', function($val) {
        // called when the classConstructed event is emitted
    })
    ->on('preRunEvent', function($val) {
        // called when the preRunEvent event is emitted
    })
    ->on('postRunEvent', function($val) {
        // called when the postRunEvent event is emitted
    })
    ->on('taskFinished', function($val) {
        // called when the taskFinished event is emitted
    })

class Task
{
    private $eventEmitter;
    
    public function __construct()
    {
        $this->eventEmitter = new EventEmitter();
    }

    public function runTask(): ExtendedTask
    {
        $this->eventEmitter->emit('preRunEvent');
        
        // some task specific code

        $this->eventEmitter->emit('postRunEvent');

        $this->eventEmitter->emit('taskFinished');

        return $this;
    }
    
    public function getEventEmitter(): EventEmitter 
    {
        return $this->eventEmitter;
    }
}

$task
    ->runTask()
    ->getEventEmitter()
    ->on('classConstructed', function($val) {
        // called when the classConstructed event is emitted
    })
    ->on('preRunEvent', function($val) {
        // called when the preRunEvent event is emitted
    })
    ->on('postRunEvent', function($val) {
        // called when the postRunEvent event is emitted
    })
    ->on('taskFinished', function($val) {
        // called when the taskFinished event is emitted
    })