1. Go to this page and download the library: Download stk2k/eventstream 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/ */
stk2k / eventstream example snippets
use stk2k\eventstream\EventStream;
use stk2k\eventstream\EventSourceInterface;
use stk2k\eventstream\emitter\SimpleEventEmitter;
use stk2k\eventstream\exception\EventSourceIsNotPushableException;
use Stk2k\EventStream\Event;
class NumberEventSource implements EventSourceInterface
{
protected $numbers;
public function __construct() {
$this->numbers = ['one', 'two', 'three'];
}
public function canPush() : bool {
return false;
}
public function push(Event $event) : EventSourceInterface {
return $this;
}
public function next() {
$number = array_shift($this->numbers);
return $number ? new Event('number',$number) : null;
}
}
// create event stream and setup callback, then flush all events
(new EventStream())
->channel('my channel', new NumberEventSource(), new SimpleEventEmitter())
->listen('number', function(Event $e){
echo 'received number='.$e->getPayload(), PHP_EOL;
})
->flush();
// received number=one
// received number=two
// received number=three
// you can not push event to unpushable event source
try{
(new NumberEventSource())->push(new Even('number','four')); // throws EventSourceIsNotPushableException
}
catch(EventSourceIsNotPushableException $e){
echo 'Event not publishable.';
}
class PushableNumberEventSource extends NumberEventSource
{
public function canPush() : bool {
return true;
}
public function push(Event $event) : EventSourceInterface {
if ($event->getName() === 'number'){
$this->numbers[] = $event->getPayload();
}
return $this;
}
}
// you acn push event to pushable event source
try{
(new EventStream())
->channel('my channel')
->source((new PushableNumberEventSource())->push('number','four'))
->emitter(new SimpleEventEmitter())
->listen('number', function(Event $e){
echo 'received number='.$e->getPayload(), PHP_EOL;
})
->flush()
->push('number', 'five')
->flush();
}
catch(EventSourceIsNotPushableException $e){
echo 'Event not publishable.';
}
// received number=one
// received number=two
// received number=three
// received number=four
// received number=five
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.