OpenSwoole\Table Example - OpenSwoole Table Documentation

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Set and Get and loop through data in OpenSwoole Table

<?php

$table = new OpenSwoole\Table(1024);
$table->column('name', OpenSwoole\Table::TYPE_STRING, 64);
$table->column('id', OpenSwoole\Table::TYPE_INT, 4);       //1,2,4,8
$table->column('num', OpenSwoole\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('[email protected]', 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 OpenSwoole Table with OpenSwoole Server

<?php

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

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

$serv->on('connect', function($serv, $fd, $reactor_id){
    $info = $serv->getClientInfo($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();
Last updated on September 1, 2022