1. Go to this page and download the library: Download phpninjas/observable 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/ */
phpninjas / observable example snippets
use Observable\Notifier;
class MyClass {
use Notifier;
public function doSomething(){
$this->notifyObservers("did something");
}
public function doSomeEvent(){
$this->notifyObservers(new MyEvent(1,2));
}
}
$newClass = new MyClass();
$newClass->addObserver(function($expect){
echo "got $expect";
});
$newClass->addObserver(function(MyObject $o){
echo "got an object this time";
});
// runtime
$newClass->doSomething();
$newClass->doSomeEvent();
class MyEvent {
public function __construct($thing1, $things2){
$this->thing1 = $thing1;
$this->thing2 = $thing2;
}
}
$newClass = new MyClass();
$newClass->addObserver(function(MyEvent $e){
// i will ONLY get MyEvent objects, everything else will be ignored for me! YAY!
});
// DO NOT DO THIS!
$observable = new MyClass();
$observable->addObserver(function(\MyEvent)use($observable){
// this will recurse infinitely (or until stack overflow).
$observable->doSomeEvent();
});
$observable->doSomeEvent();