PHP code example of italystrap / event

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

    

italystrap / event example snippets


\do_action('my_custom_action');

\do_action('my_custom_action', $arg1, $arg2);

$data_to_modify = 'Some data to modify';
$filtered_data = \apply_filters('my_custom_filter', $data_to_modify);

$listenerProvider = new \ItalyStrap\Event\GlobalOrderedListenerProvider();
// Listen for `event_name`
$listenerProvider->addListener( 'event_name', function () { echo 'Event Called'; }, 10 );

$globalDispatcher = new \ItalyStrap\Event\GlobalDispatcher();
// This will echo 'Event Called' on `event_name`
$globalDispatcher->trigger( 'event_name' );

$listenerProvider = new \ItalyStrap\Event\GlobalOrderedListenerProvider();
// Listen for `event_name`
$listenerProvider->addListener( 'event_name', function ( array $value ) {
    // $value['some-key'] === 'some-value'; true

    // Do your stuff here in the same ways you do with filters
    return $value;
}, 10 );

/** @var array $value */
$value = [ 'some-key' => 'some-value' ];
$globalDispatcher = new \ItalyStrap\Event\GlobalDispatcher();
// This will filter '$value' on `event_name`
$filtered_value = $globalDispatcher->filter( 'event_name', $value );

use ItalyStrap\Event\GlobalDispatcher;
use ItalyStrap\Event\GlobalOrderedListenerProvider;
use ItalyStrap\Event\SubscriberRegister;
use ItalyStrap\Event\SubscriberInterface;

// Your class must implement the ItalyStrap\Event\SubscriberInterface
class MyClassSubscriber implements SubscriberInterface {

    // Now add the method from the interface and return an iterable with
    // event name and the method to executed on the event
    public function getSubscribedEvents(): iterable {
        return ['event_name' => 'methodName'];
    }

    public function methodName(/* could have some arguments */){
        // Do some stuff with hooks
    }
}

$subscriber = new MyClassSubscriber();

$globalDispatcher = new GlobalDispatcher();
$listenerProvider = new GlobalOrderedListenerProvider();
$subscriberRegister = new SubscriberRegister($listenerProvider);
$subscriberRegister->addSubscriber($subscriber);

// It will execute the subscriber MyClassSubscriber::methodName
$globalDispatcher->trigger('event_name', $some_value);
// or
$globalDispatcher->filter('event_name', $some_value);

use ItalyStrap\Event\SubscriberInterface;

class MyClassSubscriber implements SubscriberInterface {

    // Just one event => method form generator
    public function getSubscribedEvents(): iterable {
        yield 'event_name' => 'method_name';
    }

    public function methodName(/* could have some arguments if you use the ::filter() method */){
        // Do some stuff with hooks
    }
}

use ItalyStrap\Event\SubscriberInterface;

class MyClassSubscriber implements SubscriberInterface {

    // Just one event => method form Iterators
    public function getSubscribedEvents(): iterable {

        yield new \ArrayObject(['event_name' => 'methodName']);

        yield new \ItalyStrap\Config\Config(['event_name' => 'methodName']);

        yield (new \ItalyStrap\Config\Config())->add( 'event_name', 'methodName' );
    }

    public function methodName(/* could have some arguments if you use the ::filter() method */){
        // Do some stuff with hooks
    }
}

use ItalyStrap\Event\SubscriberInterface;

class MyClassSubscriber implements SubscriberInterface {

    // Just one event => method
    public function getSubscribedEvents(): iterable {
        return ['event_name' => 'method_name'];
    }

    public function methodName(/* could have some arguments if you use the ::filter() method */){
        // Do some stuff with hooks
    }
}

use ItalyStrap\Event\SubscriberInterface;

class MyClassSubscriber implements SubscriberInterface {

    // Multiple events => methods
    public function getSubscribedEvents(): iterable {
        return [
            'event_name' => 'method_name',
            'event_name2' => 'method_name2'
            // ... more event => method
        ];
    }

    public function methodName(/* could have some arguments if you use the ::filter() method */){
        // Do some stuff with hooks
    }
}

use ItalyStrap\Event\SubscriberInterface as Subscriber;

class MyClassSubscriber implements Subscriber {

    public function getSubscribedEvents(): iterable {
        // Event with method and priority (for multiple events the logic is the same as above)
        return [
            'event_name' => [
                Subscriber::CALLBACK	=> 'method_name',
                Subscriber::PRIORITY	=> 20, // 10 default
            ],
            // ... more event => method
        ];
    }

    public function methodName(/* could have some arguments if you use the ::filter() method */){
        // Do some stuff with hooks
    }
}

use ItalyStrap\Event\SubscriberInterface as Subscriber;

class MyClassSubscriber implements Subscriber {

    public function getSubscribedEvents(): iterable {
        // Event with method, priority and accepted args (for multiple events the logic is the same as above)
        return [
           'event_name' => [
               Subscriber::CALLBACK	    => 'method_name',
               Subscriber::PRIORITY	    => 20, // 10 default
               Subscriber::ACCEPTED_ARGS	=> 4 // 3 default
           ],
            // ... more event => method
       ];
    }

    public function methodName(/* could have some arguments if you use the ::filter() method */){
        // Do some stuff with hooks
    }
}

use ItalyStrap\Event\SubscriberInterface as Subscriber;

class MyClassSubscriber implements Subscriber {

    public function getSubscribedEvents(): iterable {
        // Event with methods, priority and accepted args (for multiple events the logic is the same as above)
        return [
           'event_name' => [
                [
                    Subscriber::CALLBACK	    => 'method_name',
                    Subscriber::PRIORITY	    => 20, // 10 default
                    Subscriber::ACCEPTED_ARGS	=> 4 // 3 default
                ],
                [
                    Subscriber::CALLBACK	    => 'method_name2',
                    Subscriber::PRIORITY	    => 20, // 10 default
                    Subscriber::ACCEPTED_ARGS	=> 4 // 3 default
                ],
            ],
            // ... more event => method
       ];
    }

    public function methodName(/* could have some arguments if you use the ::filter() method */){
        // Do some stuff with hooks
    }
}

use ItalyStrap\Event\GlobalDispatcher;
use ItalyStrap\Event\SubscriberRegister;
use ItalyStrap\Event\SubscriberInterface;

class MyBusinessLogic {
    public function methodOne() {
        // Do some stuff
    }
    public function methodTwo() {
        // Do some stuff
    }
    public function methodThree() {
        // Do some stuff
    }
}

class MyClassSubscriber implements SubscriberInterface {
    /**
     * @var MyBusinessLogic 
     */
    private $logic;
    public function __construct( MyBusinessLogic $logic ) {
        $this->logic = $logic;
    }

    public function getSubscribedEvents(): array {
        return [
            'event_name_one' => 'onEventNameOne',
            'event_name_two' => 'onEventNameTwo',
            'event_name_three' => 'onEventNameThree',
        ];
    }
    
    public function onEventNameOne(/* may be with some arguments if you use the ::filter() method of the dispatcher */){
        $this->logic->methodOne();
    }
    
    public function onEventNameTwo(/* may be with some arguments if you use the ::filter() method of the dispatcher */){
        $this->logic->methodTwo();
    }
    
    public function onEventNameThree(/* may be with some arguments if you use the ::filter() method of the dispatcher */){
        $this->logic->methodThree();
    }
}
$logic = new MyBusinessLogic();
$subscriber = new MyClassSubscriber( $logic );

$dispatcher = new GlobalDispatcher();
$subscriber_register = new SubscriberRegister( $dispatcher );
$subscriber_register->addSubscriber( $subscriber );

// It will execute the subscriber MyClassSubscriber::methodName
$dispatcher->trigger( 'event_name' );
// or
$dispatcher->filter( 'event_name', ['some_value'] );

// You can also remove a listener:
$subscriber_register->removeSubscriber( $subscriber );

// The instance of the subscriber you want to remove MUST BE the same instance of the subscriber you
// added earlier, and BEFORE you dispatch the event.

use ItalyStrap\Config\ConfigFactory;
use ItalyStrap\Empress\AurynConfig;
use ItalyStrap\Empress\Injector;
use ItalyStrap\Event\SubscriberRegister;
use ItalyStrap\Event\SubscribersConfigExtension;
use ItalyStrap\Event\GlobalDispatcher;
use ItalyStrap\Event\GlobalOrderedListenerProvider;
use ItalyStrap\Event\SubscriberInterface;

// From Subscriber.php
class Subscriber implements SubscriberInterface {

	public int $check = 0;

	private \stdClass $stdClass;

	public function __construct(\stdClass $stdClass) {
		$this->stdClass = $stdClass;
	}

	public function getSubscribedEvents(): array {
	    yield 'event' => $this;
	}

	public function __invoke() {
		echo 'Some text';
	}
}

// From your bootstrap.php file

// Create a new InjectorContainer
$injector = new Injector();

// This is optional, you could share the injector instance
// if you need this instance inside a class for registering stuff
// Remember that the Auryn\Injector is not a service locator
// Do not use it for locating services
$injector->share($injector);

// Now it's time to create a configuration for dependencies to inject in the AurynConfig
$dependencies = ConfigFactory::make([
    // Share the instances of the GlobalDispatcher and SubscriberRegister
    AurynConfig::SHARING	=> [
        GlobalDispatcher::class,
        SubscriberRegister::class,
    ],
    // Now add in the array all your subscribers that implement the ItalyStrap\Event\SubscriberInterface
    // The instances create are shared by default for later removing like you se above.
    SubscribersConfigExtension::SUBSCRIBERS	=> [
        Subscriber::class,
    ],
    // You can also add more configuration for the AurynConfig https://github.com/ItalyStrap/empress
]);

// This will instantiate the EventResolverExtension::class
$eventResolver = $injector->make(SubscribersConfigExtension::class, [
    // In the EventResolverExtension object you can pass a config key value pair for adding or not listener at runtime
    // from your theme or plugin options
    ':config'	=> ConfigFactory::make([
        // If the 'option_key_for_subscriber' is true than the Subscriber::class will load
        'option_key_for_subscriber' => Subscriber::class // Optional
    ]),
]);

// Create the object for the AurynConfig::class and pass the instance of $injector and the dependencies collection
$empress = new \ItalyStrap\Empress\AurynConfig($injector, $dependencies);

// Is the same as above if you want to use Auryn and you have shared the Auryn instance:
$empress = $injector->make(AurynConfig::class, [
    ':dependencies'  => $dependencies
]);

// Pass the $event_resolver object created earlier
$empress->extend($eventResolver);

// When you are ready call the resolve() method for auto-wiring your application
$empress->resolve();


$this->expectOutputString( 'Some text' );
($injector->make(GlobalDispatcher::class))->trigger('event');
// or
$dispatcher = $injector->make(GlobalDispatcher::class);
$dispatcher->trigger('event');

// $dispatcher will be the same instance because you have shared it in the above code

use ItalyStrap\Config\ConfigFactory;
use ItalyStrap\Empress\AurynConfig;
use ItalyStrap\Empress\Injector;
use ItalyStrap\Event\SubscriberRegister;
use ItalyStrap\Event\SubscribersConfigExtension;
use ItalyStrap\Event\GlobalDispatcher;
use ItalyStrap\Event\GlobalOrderedListenerProvider;
use ItalyStrap\Event\SubscriberInterface;

// From MyBusinessLogic.php
class MyBusinessLogic {
    public function __construct(/*Heavy dependencies*/){
        // Initialize
    }
    public function methodOne() {
        // Do some stuff
    }
    public function methodTwo() {
        // Do some stuff
    }
    public function methodThree() {
        // Do some stuff
    }
}
// From MyClassSubscriber.php
class MyClassSubscriber implements SubscriberInterface {

    private MyBusinessLogic $logic;
    public function __construct(MyBusinessLogic $logic) {
        // This will be the proxy version of the $logic object
        $this->logic = $logic;
    }

    public function getSubscribedEvents(): array {
        // The first method that will be called will sobstitute the
        // proxy version of the object with the real one.
        return [
            'event_name_one'    => 'onEventNameOne',
            'event_name_two'    => 'onEventNameTwo',
            'event_name_three'  => 'onEventNameThree',
        ];
    }

    public function onEventNameOne(/* may be with some arguments if you use the ::filter() method of the dispatcher */){
        $this->logic->methodOne();
    }
    
    public function onEventNameTwo(/* may be with some arguments if you use the ::filter() method of the dispatcher */){
        $this->logic->methodTwo();
    }
    
    public function onEventNameThree(/* may be with some arguments if you use the ::filter() method of the dispatcher */){
        $this->logic->methodThree();
    }
}

// From your bootstrap.php file

// Create a new InjectorContainer
$injector = new Injector();

// This is optional, you could share the injector instance
// if you need this instance inside a class for registering stuff
// Remember that the Auryn\Injector is not a service locator
// Do not use it for locating services
$injector->share($injector);

// Now it's time to create a configuration for dependencies to inject in the AurynConfig
$dependencies = ConfigFactory::make([
    // Share the instances of the GlobalDispatcher and SubscriberRegister
    AurynConfig::SHARING	=> [
        GlobalDispatcher::class,
        SubscriberRegister::class,
    ],
    // Now we declare what class we need to lazy load
    // In our case is the MyBusinessLogic::class injected in the MyClassSubscriber::class
    AurynConfig::PROXY  => [
        MyBusinessLogic::class,
    ],
    // Now add in the array all your subscribers that implement the ItalyStrap\Event\SubscriberInterface
    // The instances create are shared by default for later removing like you se above.
    SubscribersConfigExtension::SUBSCRIBERS	=> [
        MyClassSubscriber::class,
    ],
    // You can also add more configuration for the AurynConfig https://github.com/ItalyStrap/empress
]);

// This will instantiate the EventResolverExtension::class
$event_resolver = $injector->make( SubscribersConfigExtension::class, [
    // In the EventResolverExtension object you can pass a config key value pair for adding or not listener at runtime
    // from your theme or plugin options
    ':config'	=> ConfigFactory::make([
        // If the 'option_key_for_subscriber' is true than the Subscriber::class will load
        'option_key_for_subscriber' => Subscriber::class // Optional
    ]),
] );

// Create the object for the AurynConfig::class and pass the instance of $injector and the dependencies collection
$empress = new AurynConfig( $injector, $dependencies );

// Is the same as above if you want to use Auryn and you have shared the Auryn instance:
$empress = $injector->make( AurynConfig::class, [
    ':dependencies'  => $dependencies
] );

// Pass the $event_resolver object created earlier
$empress->extend( $event_resolver );

// When you are ready call the resolve() method for auto-wiring your application
$empress->resolve();

$dispatcher = $injector->make(GlobalDispatcher::class);
$dispatcher->trigger('event_name_one');
$dispatcher->trigger('event_name_two');
$dispatcher->trigger('event_name_three');

\do_action('save_post', [$proxyObject, 'executeOnlyOnSavePost']);