pupper / pupper-php
PHP components for Pupper
Requires
- amphp/aerys: ^0.6.0
- roave/security-advisories: dev-master
This package is not auto-updated.
Last update: 2020-08-22 06:02:36 UTC
README
Pupper stands for "PHP Plus React" (PPR > Pupper). The goal is to make a Framework that takes the best of both technologies and makes them communicate bi-directionnaly.
Quick start
Pupper PHP is based on Aerys, a non-blocking PHP application and Websocket framework.
Here is a quick overview of the code to get started.
use Pupper\Pupper\Event; // Initiates WebSocket connection $websocket = (new Pupper\Pupper\WebSocket) // Filter allowed clients (optional) ->allowOrigin('https', 'your.domain.com', 443); // Defines a callback for 'my_event' ->addEventListener('my_event', function (Event $event) { // Dispatches to all clients $websocket->broadcastEvent( new Event('notify_all', 'Something has happened!'); ); // Dispatches to the client that triggered the callback return (new Event) ->setName('operation_done') ->setValue('Your value was ' . $event->getValue()); }); $router = Aerys\router()->route('GET', '/', Aerys\websocket($websocket)); // Exposes the websocket to the 1337 port return (new Aerys\Host)->use($router)->expose('*', 1337);
API
WebSocket
WebSocket
is the class that initiates the WebSocket on the PHP side.
addListener
addListener
takes the event name as first parameter, and a callback function as a second parameter.
If you return
an Event
, it will be dispatched to the client that triggered the callback.
use Pupper\Pupper\Event; $websocket = (new Pupper\Pupper\WebSocket) ->addEventListener('custom', function (Event $event) { return (new Event) ->setName('custom') ->setValue('From PHP: ' . $event->getValue()); });
broadcastEvent
broadcastEvent
dispatches an event to all the clients.
use Pupper\Pupper\Event; $websocket = (new Pupper\Pupper\WebSocket) ->addEventListener('player_has_joined', function (Event $event) { $websocket->broadcastEvent( 'player_count_updated', 'A new player has joined!' ); });
Client filtering
Set WebSocket's constructor's protocol, host and port parameters to restrict the access to your websocket .
$websocket = (new \Pupper\WebSocket)->allowOrigin('https', 'your.domain.com', 80);
Event
Event
represents an event from the PHP side.
Read
Event
has getName()
and getValue()
methods to read the event's name and value.
use Pupper\Pupper\Event; function (Event $event) { echo $event->getName(); echo $event->getValue(); });
Write
Event
has setName()
and setValue()
methods to write the event's name and value.
use Pupper\Pupper\Event; $event = (new Event) ->setName('hello_event') ->setValue('Hello from PHP!');
Construct
Event
's constructor also accepts the event's name and value as parameters.
use Pupper\Pupper\Event; $event = new Event( 'hello_event', 'Hello from PHP!' );
Credits
License
Unlicense. Please see License File for more information.