Swoole\Table Example - Swoole Table Documentation

Set and Get and loop through data in Swoole Table

<?php

$table = new Swoole\Table(1024);
$table->column('name', Swoole\Table::TYPE_STRING, 64);
$table->column('id', Swoole\Table::TYPE_INT, 4);       //1,2,4,8
$table->column('num', Swoole\Table::TYPE_FLOAT);
$table->create();

$table->set('a', array('id' => 1, 'name' => 'swoole-co-uk', 'num' => 3.1415));
$table->set('b', array('id' => 2, 'name' => "swoole-uk", 'num' => 3.1415));
$table->set('hello@swoole.co.uk', array('id' => 3, 'name' => 'swoole', 'num' => 3.1415));

var_dump($table->get('a'));
var_dump($table->get('b', 'name'));

foreach($table as $key => $value)
{
    var_dump($key, $value);
}

$table->del('a');

var_dump('count ' . $table->count());

Use Swoole Table with Swoole Server

<?php

// create table
$table = new Swoole\Table(1024);
$table->column('fd', Swoole\Table::TYPE_INT);
$table->column('reactor_id', Swoole\Table::TYPE_INT);
$table->column('data', Swoole\Table::TYPE_STRING, 64);
$table->create();

$serv = new Swoole\Server('127.0.0.1', 9501);
$serv->set(['dispatch_mode' => 1]);
$serv->table = $table;

$serv->on('connect', function($serv, $fd, $reactor_id){
    $info = $serv->connection_info($fd);
    $serv->send($fd, "INFO: fd=$fd, reactor_id=$reactor_id, addr=$info['remote_ip']:$info['remote_port']\n");
});

$serv->on('receive', function ($serv, $fd, $reactor_id, $data) {
    $cmd = explode(" ", trim($data));
    if ($cmd[0] == 'get')
    {
        if (count($cmd) < 2)
        {
            $cmd[1] = $fd;
        }
        $get_fd = intval($cmd[1]);
        $info = $serv->table->get($get_fd);
        $serv->send($fd, var_export($info, true)."\n");
    }
    else if ($cmd[0] == 'set')
    {
        $ret = $serv->table->set($fd, array('reactor_id' => $data, 'fd' => $fd, 'data' => $cmd[1]));
        if ($ret === false)
        {
            $serv->send($fd, "ERROR\n");
        }
        else
        {
            $serv->send($fd, "OK\n");
        }
    }
    else
    {
        $serv->send($fd, "command error.\n");
    }
});
$serv->start();