DEV Community

sebk69
sebk69

Posted on

Let's demystify swoole : tables

Introduction

Swoole provide a table system based on memory.

These tables are stored in memory with very high speed access and accessible to every thread and processes.

Creating your first table

To create table, use Swoole\Table object :

$members = new Swoole\Table(500);
Enter fullscreen mode Exit fullscreen mode

The parameter represent max entries managed by table. Adjust the size to avoid using too much memory.

We will now declare fields :

$members->column('firstname', Swoole\Table::TYPE_STRING);
$members->column('lastname', Swoole\Table::TYPE_STRING);
Enter fullscreen mode Exit fullscreen mode

And create the table :

$members->create();
Enter fullscreen mode Exit fullscreen mode

Insert/update data

We can now use the table.

Use set method to persist records :

foreach ([
    ['firstname' => 'john', 'lastname' => 'doe'],
    ['firstname' => 'paul', 'lastname' => 'carbon']
] as $key => $record) {
    $members->set($key, $record);
}
Enter fullscreen mode Exit fullscreen mode

And same for update :

$members->set(0, ['firstname' => 'john the second', 'lastname' => 'doe']);
Enter fullscreen mode Exit fullscreen mode

Getting data

You can access data from key :

$key = 0;
$member = $members->get($key);
Enter fullscreen mode Exit fullscreen mode

And if you need only one field :

$key = 0;
$field = 'firstname';
$firstname = $members->get($key, $field);
Enter fullscreen mode Exit fullscreen mode

You can also iterate all records with foreach :

foreach ($members as $key => $record) {
    echo 'member #' . $key . ' : ' . $record['firstname'] . ' ' . $record['lastname'];
}
Enter fullscreen mode Exit fullscreen mode

Delete a record

To remove a record, use :

$key = 0;
$members->del($key);
Enter fullscreen mode Exit fullscreen mode

Other posts on swoole

Top comments (0)