Swoole Table Example

Basic usage of Swoole Table API, Access as Array:

<?php

$table = new swoole_table(1024);
$table->column('id', swoole_table::TYPE_INT);
$table->column('name', swoole_table::TYPE_STRING, 64);
$table->column('num', swoole_table::TYPE_FLOAT);
$table->create();

$table['apple'] = array('id' => 145, 'name' => 'iPhone', 'num' => 3.1415);
$table['google'] = array('id' => 358, 'name' => "AlphaGo", 'num' => 3.1415);
$table['microsoft']['name'] = "Windows";
$table['microsoft']['num'] = '1997.03';

var_dump($table['apple']);
var_dump($table['microsoft']);
$table['google']['num'] = 500.90;
var_dump($table['google']);

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");
    }
    elseif ($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();