PHP code example of initphp / events

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

    

initphp / events example snippets




use InitPHP\Events\Events;

Events::on('helloTrigger', function (): void {
    echo 'Hello World' . PHP_EOL;
}, 100);

Events::on('helloTrigger', function (): void {
    echo 'Hi, World' . PHP_EOL;
}, 99);

Events::trigger('helloTrigger');

Events::on('greet', function (string $name, string $me): void {
    echo "Hi {$name}. I am {$me}." . PHP_EOL;
}, 99);

Events::trigger('greet', 'World', 'John');
// Hi World. I am John.

Events::on('save', function ($payload) {
    if (!isValid($payload)) {
        return false;          // stops the chain
    }
}, 10);

Events::on('save', function ($payload): void {
    persist($payload);         // never runs if validation returned false
}, 20);

if (!Events::trigger('save', $payload)) {
    // at least one listener vetoed the operation
}

use InitPHP\Events\Event;

$dispatcher = new Event();

$dispatcher
    ->on('user.registered', function ($user): void {
        sendWelcomeEmail($user);
    })
    ->on('user.registered', function ($user): void {
        trackSignup($user);
    }, Event::PRIORITY_LOW);    // run last

$dispatcher->trigger('user.registered', $user);

use InitPHP\Events\EventEmitter;

$emitter = new EventEmitter();

$emitter->on('hello', function (string $name): void {
    echo "Hello {$name}!" . PHP_EOL;
}, 99);

$emitter->once('hello', function (string $name): void {
    echo "Hi {$name}, this only fires once." . PHP_EOL;
}, 10);

$emitter->emit('hello', ['World']);
$emitter->emit('hello', ['World']);

$dispatcher->once('boot', $listener);          // fires at most once
$dispatcher->off('boot', $listener);           // removes a specific listener
$dispatcher->removeAllListeners('boot');       // wipes one event
$dispatcher->removeAllListeners();             // wipes every event

$dispatcher = new InitPHP\Events\Event();
$dispatcher->setSimulate(true);   // listeners are not invoked; trigger() still returns true
$dispatcher->setDebugMode(true);  // each trigger() appends {start, end, event} to the log

$dispatcher->trigger('checkout.complete', $order);

$dispatcher->getDebug();          // [['start' => ..., 'end' => ..., 'event' => 'checkout.complete']]
$dispatcher->clearDebug();        // empty the log

// Before
use InitPHP\EventEmitter\EventEmitter;

// After
use InitPHP\Events\EventEmitter;