PHP code example of derywat / php-events

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

    

derywat / php-events example snippets


use derywat\events\EventInterface;

class MyCustomEventClass implements EventInterface {

	protected $message;

	public function __construct(string $message){
		$this->message = $message;
	}

	public function __tostring(): string {
		return "{$this->message}";
	}

}

use derywat\events\EventsProducerInterface;
use derywat\events\EventsProducerTrait;

class MyClass implements EventsProducerInterface {
	use EventsProducerTrait;

	protected function myMethodWithEvent(){
		//report event
		$this->reportEvent(new MyCustomEventClass("message to send in event"));
	}
}

use derywat\events\EventsReceiverInterface;

class MyEventReceivingClass implements EventsReceiverInterface {
	
	public function eventHandler(EventInterface $event):void {
		$class = get_class($event);
		switch($class) {  
			case MyCustomEventClass::class:
				//handle events of MyCustomEventClass here
				break;
		}
	}

}


$receiverInstance = new MyEventReceivingClass();
$producerInstance = new MyClass();
//register receiver in producer
$producerInstance->registerEventReceiver($receiverInstance);

use derywat\events\EventsReceiverInterface;
use derywat\events\EventReceiverTrait;

class MyEventReceivingClass implements EventsReceiverInterface {
	use EventReceiverTrait;
}

use derywat\events\EventsReceiver;

$receiverInstance = new MyEventReceivingClass();
$receiverInstance->addEventHandlerClosure(
	function(EventInterface $event):void {
		$class = get_class($event);
		switch($class) {  
			case MyCustomEventClass::class:
				//handle events of MyCustomEventClass here
				break;
		}
	}
);

$producerInstance = new MyClass();
$producerInstance->registerEventReceiver($receiverInstance);

use derywat\events\EventsReceiver;

$producerInstance = new MyClass();

$producerInstance->registerEventReceiver(
	//create instance of EventsReceiver
	(new EventsReceiver())->addEventHandlerClosure(
		function(EventInterface $event):void {
			$class = get_class($event);
			switch($class) {  
    			case MyCustomEventClass::class:
			        //handle events of MyCustomEventClass here
			        break;
			}
		}
	)
);