PHP code example of pe / component-event

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

    

pe / component-event example snippets


namespace PE\Component\Event;

// Create emitter instance, maybe in some DI container
$emitter = new Emitter();

// Attach listener to some event
$emitter->attach('event_name', function ($foo, $bar) {
    // do something
});
// Also you can attach as generic listener for allow stop propagation
$emitter->attach('event_name', function (Event $event) {
    $event->stop();// <-- call for stop propagation
});

// Dispatch event somewhere in logic
$emitter->dispatch(new Event('event_name', $foo, $bar));


namespace PE\Component\Event;

// Create your own event class for store specific payload or modify it in listeners
class SomeEvent
{
    public string $message = 'A';
}

$emitter = new Emitter();

// Listener A, it's important to first arg be same as event class
$emitter->attach(SomeEvent::class, function (SomeEvent $event) {
    $event->message = 'B';
});
// Listener B
$emitter->attach(SomeEvent::class, function (SomeEvent $event) {
    echo $event->message;// <-- here message is "B"
});
$emitter->dispatch(new SomeEvent());

php composer.phar