PHP code example of tarantool / client

1. Go to this page and download the library: Download tarantool/client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tarantool / client example snippets


use Tarantool\Client\Client;

$client = Client::fromDefaults();

use Tarantool\Client\Client;

$client = Client::fromDsn('tcp://127.0.0.1');
$client = Client::fromDsn('tcp://[fe80::1]:3301');
$client = Client::fromDsn('tcp://user:[email protected]:3301');
$client = Client::fromDsn('tcp://[email protected]/?connect_timeout=5.0&max_retries=3');
$client = Client::fromDsn('unix:///var/run/tarantool/my_instance.sock');
$client = Client::fromDsn('unix://user:pass@/var/run/tarantool/my_instance.sock?max_retries=3');

use Tarantool\Client\Client;

$client = Client::fromOptions([
    'uri' => 'tcp://127.0.0.1:3301',
    'username' => '<username>',
    'password' => '<password>',
    ...
);

use MessagePack\BufferUnpacker;
use MessagePack\Packer;
use Tarantool\Client\Client;
use Tarantool\Client\Connection\StreamConnection;
use Tarantool\Client\Handler\DefaultHandler;
use Tarantool\Client\Handler\MiddlewareHandler;
use Tarantool\Client\Middleware\AuthenticationMiddleware;
use Tarantool\Client\Middleware\RetryMiddleware;
use Tarantool\Client\Packer\PurePacker;

$connection = StreamConnection::createTcp('tcp://127.0.0.1:3301', [
    'socket_timeout' => 5.0,
    'connect_timeout' => 5.0,
    // ...
]);

$pureMsgpackPacker = new Packer();
$pureMsgpackUnpacker = new BufferUnpacker();
$packer = new PurePacker($pureMsgpackPacker, $pureMsgpackUnpacker);

$handler = new DefaultHandler($connection, $packer);
$handler = MiddlewareHandler::append($handler, [
    RetryMiddleware::exponential(3),
    new AuthenticationMiddleware('<username>', '<password>'),
    // ...
]);

$client = new Client($handler);

use Tarantool\Client\Keys;
use Tarantool\Client\Request\CallRequest;

...

$request = new CallRequest('box.stat');
$response = $handler->handle($request);
$data = $response->getBodyField(Keys::DATA);

use Tarantool\Client\Client;
use Tarantool\Client\Middleware\AuthenticationMiddleware;

$client = Client::fromDefaults()->withMiddleware(
    new AuthenticationMiddleware('<username>', '<password>')
);

use Tarantool\Client\Client;
use Tarantool\Client\Middleware\FirewallMiddleware;
use Tarantool\Client\Middleware\LoggingMiddleware;
use Tarantool\Client\Middleware\RetryMiddleware;

...

$client = Client::fromDefaults()->withMiddleware(
    FirewallMiddleware::allowReadOnly(),
    RetryMiddleware::linear(),
    new LoggingMiddleware($logger)
);

$client1 = Client::fromDefaults()->withMiddleware(
    RetryMiddleware::linear(),
    new AuthenticationMiddleware('<username>', '<password>') 
);

$client2 = Client::fromDefaults()->withMiddleware(
    new AuthenticationMiddleware('<username>', '<password>'), 
    RetryMiddleware::linear()
);

$client3 = Client::fromOptions([
    'username' => '<username>',
    'password' => '<password>',
])->withMiddleware(RetryMiddleware::linear());

$client = $client->withPrependedMiddleware($myMiddleware);

$space = $client->getSpace('example');
$result1 = $space->select(Criteria::key([1]));
$result2 = $space->select(Criteria::index('secondary')
    ->andKey(['bar'])
    ->andLimit(2)
    ->andOffset(1)
);

printf("Result 1: %s\n", json_encode($result1));
printf("Result 2: %s\n", json_encode($result2));

$space = $client->getSpace('example');
$result = $space->insert([1, 'foo', 'bar']);

printf("Result: %s\n", json_encode($result));

$space = $client->getSpace('example');
$result = $space->update([2], Operations::add(1, 5)->andSet(2, 'BAR'));

// Since Tarantool 2.3 you can refer to tuple fields by name:
// $result = $space->update([2], Operations::add('num', 5)->andSet('name', 'BAR'));

printf("Result: %s\n", json_encode($result));

$space = $client->getSpace('example');
$space->upsert([1, 'foo', 'bar'], Operations::set(1, 'baz'));
$space->upsert([1, 'foo', 'bar'], Operations::set(2, 'qux'));

// Since Tarantool 2.3 you can refer to tuple fields by name:
// $space->upsert([1, 'foo', 'bar'], Operations::set('name1', 'baz'));
// $space->upsert([1, 'foo', 'bar'], Operations::set('name2'', 'qux'));

$space = $client->getSpace('example');
$result1 = $space->replace([2, 'BAR']);
$result2 = $space->replace([3, 'BAZ']);

printf("Result 1: %s\n", json_encode($result1));
printf("Result 2: %s\n", json_encode($result2));

$space = $client->getSpace('example');
$result1 = $space->delete([2]);
$result2 = $space->delete(['baz'], 'secondary');

printf("Result 1: %s\n", json_encode($result1));
printf("Result 2: %s\n", json_encode($result2));

$result1 = $client->call('func_42');
$result2 = $client->call('math.min', 5, 3, 8);

printf("Result 1: %s\n", json_encode($result1));
printf("Result 2: %s\n", json_encode($result2));

$result1 = $client->evaluate('function func_42() return 42 end');
$result2 = $client->evaluate('return func_42()');
$result3 = $client->evaluate('return math.min(...)', 5, 3, 8);

printf("Result 1: %s\n", json_encode($result1));
printf("Result 2: %s\n", json_encode($result2));
printf("Result 3: %s\n", json_encode($result3));

$client->execute('CREATE TABLE users ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "email" VARCHAR(255))');

$result1 = $client->executeUpdate('CREATE UNIQUE INDEX email ON users ("email")');

$result2 = $client->executeUpdate('
    INSERT INTO users VALUES (null, :email1), (null, :email2)
',
    [':email1' => '[email protected]'],
    [':email2' => '[email protected]']
);

$result3 = $client->executeQuery('SELECT * FROM users WHERE "email" = ?', '[email protected]');
$result4 = $client->executeQuery('SELECT * FROM users WHERE "id" IN (?, ?)', 1, 2);

printf("Result 1: %s\n", json_encode([$result1->count(), $result1->getAutoincrementIds()]));
printf("Result 2: %s\n", json_encode([$result2->count(), $result2->getAutoincrementIds()]));
printf("Result 3: %s\n", json_encode([$result3->count(), $result3[0]]));
printf("Result 4: %s\n", json_encode(iterator_to_array($result4)));

$response = $client->execute('<any-type-of-sql-statement>');
$resultSet = $response->tryGetBodyField(Keys::DATA);

if ($resultSet === null) {
    $sqlInfo = $response->getBodyField(Keys::SQL_INFO);
    $affectedCount = $sqlInfo[Keys::SQL_INFO_ROW_COUNT];
} 

$client->execute('CREATE TABLE users ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "name" VARCHAR(50))');

$stmt = $client->prepare('INSERT INTO users VALUES(null, ?)');
for ($i = 1; $i <= 100; ++$i) {
    $stmt->execute("name_$i");
    // You can also use executeSelect() and executeUpdate(), e.g.:
    // $lastInsertIds = $stmt->executeUpdate("name_$i")->getAutoincrementIds();
}
$stmt->close();

// Note the SEQSCAN keyword in the query. It is available as of Tarantool 2.11.
// If you are using an older version of Tarantool, omit this keyword.
$result = $client->executeQuery('SELECT COUNT("id") AS "cnt" FROM SEQSCAN users');

printf("Result: %s\n", json_encode($result[0]));

$space->insert([42, Money::EUR(500)]);
[[$id, $money]] = $space->select(Criteria::key([42]));

$packer = PurePacker::fromExtensions(new MoneyExtension());
$client = new Client(new DefaultHandler($connection, $packer));
lua
function func_42()
    return 42
end
bash
PHP_IMAGE='php:8.2-cli' ./dockerfile.sh | docker build -t client -
bash
docker network create tarantool-php
docker run -d --net=tarantool-php -p 3301:3301 --name=tarantool \
    -v $(pwd)/tests/Integration/client.lua:/client.lua \
    tarantool/tarantool:3 tarantool /client.lua
bash
docker run --rm --net=tarantool-php -v $(pwd):/client -w /client client