1. Go to this page and download the library: Download machinateur/php-sse 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/ */
machinateur / php-sse example snippets
namespace App;
use Machinateur\SSE\MessageStream;
use Machinateur\SSE\Exception\TimeoutException;
// ...
$stream = new MessageStream();
// ...
// Count to 10, then quit at 5.
$stream->run(function () {
foreach (\range(1, 10, 1) as $i) {
if ($i > 5) {
throw TimeoutException::toTriggerStreamShutdown();
}
yield $i;
\sleep(1);
}
});
$stream = new \Machinateur\SSE\MessageStream();
$stream->setLogger($myLogger);
// ...
namespace App;
use Machinateur\SSE\Exception\TimeoutException;
use Machinateur\SSE\MessageStream;
use Machinateur\SSE\MessageStreamInterface;
use Machinateur\SSE\Message\MessageInterface;
/**
* A naive implementation of {@see MessageStreamInterface}.
*/
class CustomMessageStream extends MessageStream implements MessageStreamInterface
{
/**
* @inheritDoc
*/
public function run(callable $callback)
{
try {
foreach ($callback() as $message) {
\assert($message instanceof MessageInterface);
$this->printOutput($message->getMessageFormat());
$this->checkConnection();
}
} catch (TimeoutException $exception) {
}
}
}
// ...
$stream = new CustomMessageStream();
namespace App;
use Machinateur\SSE\Format\StreamFormat;
use Machinateur\SSE\Message\MessageInterface;
/**
* Custom message to be yielded by a generator function. It holds a data array, which is given to `json_encode()`
* when sent by the message stream.
*/
class CustomMessage implements MessageInterface
{
const FLAGS = \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_PRESERVE_ZERO_FRACTION;
/** @var array */
private $data = array();
/**
* @param array $data
*/
public function setData($data)
{
$this->data = $data;
}
/**
* @inheritDoc
*/
public function getStreamFormat()
{
return [
StreamFormat::FIELD_COMMENT => 'source: ' . self::class,
StreamFormat::FIELD_DATA => \json_encode($this->data, self::FLAGS)
];
}
}