Building a Wrapper

Learning by example and explaining using code samples seem to be very effective in programming, so I will try to explain how wrappers work with a simple example. And of course it is going to be a chat example.. It will be the simplest of chats - you connect and start typing. Each message that you send is going to be broadcasted to the rest of the clients currently connected to the server.

The Wrapper base class

Your wrappers classes will all be inheriting from the abstract Wrapper class. Please go get familiar with it before you continue.

Where to put your wrapper file?

Each wrapper gets its own directory under the wrappers/ directory. The name of our wrapper will be DemoChat, so we should put our files inside wrappers/DemoChat/. The main file should be wrappers/DemoChat/DemoChat.php.

DemoChat.php

Ok, now that we have the wrapper file in the correct place, lets see what it would look like.


class DemoChat extends Wrapper {
    private $clients;

    public function init() {
        $this->clients = array();
    }

    public function onConnect($con) {
        $this->clients[$con->id] = $con;
    }

    public function onDisconnect($con) {
        unset($this->clients[$con->id]);
    }

    public function onData($con, $data) {
        foreach ($this->clients as $client) {
            if ($client->id != $con->id) {
                $client->send("> " . $data);
            }
        }
    }

    public function onStop() {}
}
  

Sample config.php

Suppose that we want to start our server at port 8080 we would have the following config:


$server_config = array(
    8080 => array(
        'DemoChat' => array(),
        'ssl' => array(
            'cert_file' => '',
            'privkey_file' => '',
            'passphrase' => ''
        )
    )
);
  

Testing it out

Run the server.php file in a terminal like so php server.php then open two other teminals. Use telnet to connect to the server on both of them like so telnet localhost 8080. Type something in one of them and hit <enter>. You should see your message in the other terminal.

That's it. If you have any questions feel free to open an issue in GitHub.