yandex-cloud/ydb-php-sdk 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

yandex-cloud/ydb-php-sdk

Composer 安装命令:

composer require yandex-cloud/ydb-php-sdk

包简介

YDB PHP SDK

README 文档

README

YDB PHP SDK provides access to YDB from PHP code.

YDB is a open-source distributed fault-tolerant DBMS with high availability and scalability, strict consistency and ACID. An SQL dialect – YQL – is used for queries.

YDB is available in several modes:

  • On-prem installation (is not supported by this SDK yet);
  • Serverless computing mode in YC (only performed operations are paid);
  • Dedicated instance mode in YC (dedicated computing resources are paid).

Documentation

https://ydb.tech/docs/

Installation

The recommended method of installing is Composer.

Run the following:

composer require ydb-platform/ydb-php-sdk

Connection

First, create a database using Yandex Cloud Console.

YDB supports the following authentication methods:

  • Access token
  • OAuth token
  • JWT + private key
  • JWT + JSON file
  • Metadata URL
  • Anonymous

Access token

Use your access token:

<?php

use YdbPlatform\Ydb\Ydb;

$config = [

    // Database path
    'database'    => '/ru-central1/b1glxxxxxxxxxxxxxxxx/etn0xxxxxxxxxxxxxxxx',

    // Database endpoint
    'endpoint'    => 'ydb.serverless.yandexcloud.net:2135',

    // Auto discovery (dedicated server only)
    'discovery'   => false,

    // IAM config
    'iam_config'  => [
        'root_cert_file' => './CA.pem', // Root CA file (dedicated server only!)

        // Access token authentication
        'access_token'    => 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
    ],
];

$ydb = new Ydb($config);

or:

<?php

use YdbPlatform\Ydb\Ydb;
use YdbPlatform\Ydb\Auth\Implement\AccessTokenAuthentication;

$config = [

    // Database path
    'database'    => '/ru-central1/b1glxxxxxxxxxxxxxxxx/etn0xxxxxxxxxxxxxxxx',

    // Database endpoint
    'endpoint'    => 'ydb.serverless.yandexcloud.net:2135',

    // Auto discovery (dedicated server only)
    'discovery'   => false,

    // IAM config
    'iam_config'  => [
        'root_cert_file' => './CA.pem', // Root CA file (dedicated server only!)
    ],
    
    'credentials' => new AccessTokenAuthentication('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
];

$ydb = new Ydb($config);

OAuth token

You should obtain a new OAuth token.

Use your OAuth token:

<?php

use YdbPlatform\Ydb\Ydb;

$config = [

    // Database path
    'database'    => '/ru-central1/b1glxxxxxxxxxxxxxxxx/etn0xxxxxxxxxxxxxxxx',

    // Database endpoint
    'endpoint'    => 'ydb.serverless.yandexcloud.net:2135',

    // Auto discovery (dedicated server only)
    'discovery'   => false,

    // IAM config
    'iam_config'  => [
        'temp_dir'       => './tmp', // Temp directory
        'root_cert_file' => './CA.pem', // Root CA file (dedicated server only!)

        // OAuth token authentication
        'oauth_token'    => 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
    ],
];

$ydb = new Ydb($config);

or

<?php

use YdbPlatform\Ydb\Ydb;
use YdbPlatform\Ydb\Auth\Implement\OAuthTokenAuthentication;

$config = [

    // Database path
    'database'    => '/ru-central1/b1glxxxxxxxxxxxxxxxx/etn0xxxxxxxxxxxxxxxx',

    // Database endpoint
    'endpoint'    => 'ydb.serverless.yandexcloud.net:2135',

    // Auto discovery (dedicated server only)
    'discovery'   => false,

    // IAM config
    'iam_config'  => [
        'temp_dir'       => './tmp', // Temp directory
        'root_cert_file' => './CA.pem', // Root CA file (dedicated server only!)
    ],
    
    'credentials' => new OAuthTokenAuthentication('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
];

$ydb = new Ydb($config);

JWT + private key

Create a service account with the editor role, then create a private key. Also you need a key ID and a service account ID.

Connect to your database:

<?php

use YdbPlatform\Ydb\Ydb;

$config = [
    'database'    => '/ru-central1/b1glxxxxxxxxxxxxxxxx/etn0xxxxxxxxxxxxxxxx',
    'endpoint'    => 'ydb.serverless.yandexcloud.net:2135',
    'discovery'   => false,
    'iam_config'  => [
        'temp_dir'           => './tmp', // Temp directory
        'root_cert_file'     => './CA.pem', // Root CA file (dedicated server only!)

        // Private key authentication
        'key_id'             => 'ajexxxxxxxxx',
        'service_account_id' => 'ajeyyyyyyyyy',
        'private_key_file'   => './private.key',
    ],
];

$ydb = new Ydb($config);

or

<?php

use YdbPlatform\Ydb\Ydb;
use YdbPlatform\Ydb\Auth\Implement\JwtWithPrivateKeyAuthentication;

$config = [
    'database'    => '/ru-central1/b1glxxxxxxxxxxxxxxxx/etn0xxxxxxxxxxxxxxxx',
    'endpoint'    => 'ydb.serverless.yandexcloud.net:2135',
    'discovery'   => false,
    'iam_config'  => [
        'temp_dir'           => './tmp', // Temp directory
        'root_cert_file'     => './CA.pem', // Root CA file (dedicated server only!)

        // Private key authentication
        'key_id'             => 'ajexxxxxxxxx',
        'service_account_id' => 'ajeyyyyyyyyy',
        'private_key_file'   => './private.key',
    ],
    
    'credentials' => new JwtWithPrivateKeyAuthentication(
        "ajexxxxxxxxx","ajeyyyyyyyyy",'./private.key')
        
];

$ydb = new Ydb($config);

JWT + JSON file

Create a service account with the editor role.

Create a service account JSON file, save it in your project as sa_name.json.

Connect to your database:

<?php

use YdbPlatform\Ydb\Ydb;

$config = [
    'database'    => '/ru-central1/b1glxxxxxxxxxxxxxxxx/etn0xxxxxxxxxxxxxxxx',
    'endpoint'    => 'ydb.serverless.yandexcloud.net:2135',
    'discovery'   => false,
    'iam_config'  => [
        'temp_dir'       => './tmp', // Temp directory
        'root_cert_file' => './CA.pem', // Root CA file (dedicated server only!)

        // Service account JSON file authentication
        'service_file'   => './sa_name.json',
    ],
];

$ydb = new Ydb($config);

or:

<?php

use YdbPlatform\Ydb\Ydb;
use YdbPlatform\Ydb\Auth\Implement\JwtWithJsonAuthentication;

$config = [
    'database'    => '/ru-central1/b1glxxxxxxxxxxxxxxxx/etn0xxxxxxxxxxxxxxxx',
    'endpoint'    => 'ydb.serverless.yandexcloud.net:2135',
    'discovery'   => false,
    'iam_config'  => [
        'temp_dir'       => './tmp', // Temp directory
        'root_cert_file' => './CA.pem', // Root CA file (dedicated server only!)
    ],
            
    'credentials' => new JwtWithJsonAuthentication('./jwtjson.json')
];

$ydb = new Ydb($config);

Metadata URL

When you deploy a project to VM or function at Yandex.Cloud, you are able to connect to the database using Metadata URL. Before you start, you should link your service account to an existing or new VM or function.

<?php

use YdbPlatform\Ydb\Ydb;

$config = [

    // Database path
    'database'    => '/ru-central1/b1glxxxxxxxxxxxxxxxx/etn0xxxxxxxxxxxxxxxx',

    // Database endpoint
    'endpoint'    => 'ydb.serverless.yandexcloud.net:2135',

    // Auto discovery (dedicated server only)
    'discovery'   => false,

    // IAM config
    'iam_config'  => [
        'temp_dir'     => './tmp', // Temp directory
        'use_metadata' => true,
    ],
];

$ydb = new Ydb($config);

or

<?php

use YdbPlatform\Ydb\Ydb;
use YdbPlatform\Ydb\Auth\Implement\MetadataAuthentication;

$config = [

    // Database path
    'database'    => '/ru-central1/b1glxxxxxxxxxxxxxxxx/etn0xxxxxxxxxxxxxxxx',

    // Database endpoint
    'endpoint'    => 'ydb.serverless.yandexcloud.net:2135',

    // Auto discovery (dedicated server only)
    'discovery'   => false,

    // IAM config
    'iam_config'  => [
        'temp_dir'     => './tmp', // Temp directory
    ],
    'credentials' => new MetadataAuthentication()
];

$ydb = new Ydb($config);

Anonymous

<?php

use YdbPlatform\Ydb\Ydb;

$config = [

    // Database path
    'database'    => '/local',

    // Database endpoint
    'endpoint'    => 'localhost:2136',

    // Auto discovery (dedicated server only)
    'discovery'   => false,

    // IAM config
    'iam_config'  => [
        'anonymous' => true,
        'insecure' => true,
    ],
];

$ydb = new Ydb($config);

or:

<?php

use YdbPlatform\Ydb\Ydb;
use YdbPlatform\Ydb\Auth\Implement\AnonymousAuthentication;

$config = [

    // Database path
    'database'    => '/local',

    // Database endpoint
    'endpoint'    => 'localhost:2136',

    // Auto discovery (dedicated server only)
    'discovery'   => false,

    // IAM config
    'iam_config'  => [
        'insecure' => true,
    ],
    
    'credentials' => new AnonymousAuthentication()
];

$ydb = new Ydb($config);

Determined by environment variables

<?php

use YdbPlatform\Ydb\Ydb;
use YdbPlatform\Ydb\Auth\Implement\EnvironCredentials;

$config = [

    // Database path
    'database'    => '/local',

    // Database endpoint
    'endpoint'    => 'localhost:2136',

    // Auto discovery (dedicated server only)
    'discovery'   => false,

    // IAM config
    'iam_config'  => [
        'insecure' => true,
    ],
    
    'credentials' => new EnvironCredentials()
];

$ydb = new Ydb($config);

The following algorithm that is the same for YDB-PHP-SDK applies:

  1. If the value of the YDB_SERVICE_ACCOUNT_KEY_FILE_CREDENTIALS environment variable is set, the System Account Key authentication mode is used and the key is taken from the file whose name is specified in this variable.
  2. Otherwise, if the value of the YDB_ANONYMOUS_CREDENTIALS environment variable is set to 1, the anonymous authentication mode is used.
  3. Otherwise, if the value of the YDB_METADATA_CREDENTIALS environment variable is set to 1, the Metadata authentication mode is used.
  4. Otherwise, if the value of the YDB_ACCESS_TOKEN_CREDENTIALS environment variable is set, the Access token authentication mode is used, where the this variable value is passed.
  5. Otherwise, the Metadata authentication mode is used.

Static credentials

<?php

use YdbPlatform\Ydb\Ydb;
use YdbPlatform\Ydb\Auth\Implement\StaticAuthentication;

$config = [

    // Database path
    'database'    => '/local',

    // Database endpoint
    'endpoint'    => 'localhost:2136',

    // Auto discovery (dedicated server only)
    'discovery'   => false,

    // IAM config
    'iam_config'  => [
        'insecure' => true,
    ],
    
    'credentials' => new StaticAuthentication($user, $password)
];

$ydb = new Ydb($config);

Reading from text file

<?php

use YdbPlatform\Ydb\Ydb;
use YdbPlatform\Ydb\Auth\ReadTokenFromFile;

$config = [

    // Database path
    'database'    => '/local',

    // Database endpoint
    'endpoint'    => 'localhost:2136',

    // Auto discovery (dedicated server only)
    'discovery'   => false,

    // IAM config
    'iam_config'  => [
        'insecure' => true,
    ],
    
    'credentials' => new ReadTokenFromFile($tokenPath, $refreshTime)
];

$ydb = new Ydb($config);

Usage

You should initialize a session from the Table service to start querying with retry.

<?php

use YdbPlatform\Ydb\Ydb;

$config = [
    // ...
];

$ydb = new Ydb($config);

// obtaining the Table service
$table = $ydb->table();

$result = $table->retryTransaction(function(Session $session){
    // making a query
    return $session->query('select * from `users` limit 10;');
}, true);

$users_count = $result->rowCount();
$users = $result->rows();

$columns = $result->columns();

As soon as your script is finished, the session will be destroyed.

Customizing queries

Normally, a regular query through the query() method is sufficient, but in exceptional cases, you may need to fine-tune the query settings. You could do it using the query builder:

<?php

$result = $table->retryTransaction(function(Session $session){

    // creating a new query builder instance
    $query = $session->newQuery('select * from `users` limit 10;');
    
    // a setting to keep in cache
    $query->keepInCache();
    
    // a setting to begin a transaction with the given mode
    $query->beginTx('stale');
    
    return $query->execute();
}, true);

Methods of the query builder:

  • keepInCache(bool $value) - keep in cache (default: true)
  • collectStats(int $value) - collect stats (default: 1)
  • parameters(array $parameters) - parameters
  • operationParams(\Ydb\Operations\OperationParams $operation_params) - operation params
  • beginTx(string $mode) - begin a transaction with the given mode:
    • stale
    • online
    • online_inconsistent
    • serializable
    • snapshot
  • txControl(\Ydb\Table\TransactionControl $tx_control) - transaction control with custom settings

You can chain these methods for convenience.

Logging

For logging purposes, you need use class, which implements \Psr\Log\LoggerInterface. YDB-PHP-SDK has build-in loggers in YdbPlatform\Ydb\Logger namespace:

  • NullLogger - default
  • SimpleStdLogger($level) - logger, which push logs in STDERR.

Example of using:

$config = [
    'logger' => new \YdbPlatform\Ydb\Logger\SimpleStdLogger(\YdbPlatform\Ydb\Logger\SimpleStdLogger::INFO)
]
$ydb = new \YdbPlatform\Ydb\Ydb($config);

Discovery

Endpoint discovery asks the cluster which nodes are currently serving the database, and balances subsequent requests across them. The SDK keeps the list fresh in the background and re-discovers automatically when a node becomes unavailable.

Turning it on or off

Controlled by the discovery config key. The default is false (off).

$config = [
    // ...
    'discovery' => true,
];

Turn it on for long-running processes that issue many queries per run — workers, daemons, web apps under heavy query load. You get load balancing across cluster nodes and automatic recovery when a node goes down, at the cost of one extra round-trip on startup plus a periodic background refresh.

Leave it off for short-lived scripts that make only a handful of queries — cron jobs, CLI utilities, or simple PHP pages that finish in under a minute and issue at most a couple of dozen queries to YDB. The startup cost is not worth it: a single endpoint is enough, and the script exits long before the background refresh would have mattered.

Tuning keys

These apply only when discovery => true.

discoveryInterval            default 60       seconds
discoveryInitialTimeoutMs    default 5000     milliseconds
discoveryTimeoutMs           default 1000     milliseconds
discoveryAttemptTimeoutMs    default 300      milliseconds
  • discoveryInterval — how often the background loop re-fetches the endpoint list.

  • discoveryInitialTimeoutMs — total budget for the startup discovery call in the Ydb constructor. If the cluster is unreachable for longer than this, the constructor throws. Set to PHP_INT_MAX to wait indefinitely on startup.

  • discoveryTimeoutMs — total budget for one background re-discovery iteration.

  • discoveryAttemptTimeoutMs — per-attempt gRPC deadline inside the discovery retry loop.

Example — wait forever for the cluster on startup:

$config = [
    // ...
    'discovery' => true,
    'discoveryInitialTimeoutMs' => PHP_INT_MAX,
];

For cross-region or otherwise high-latency setups, raise discoveryInitialTimeoutMs up to 15000 and triple the other two (discoveryTimeoutMs ≈ 3000, discoveryAttemptTimeoutMs ≈ 900) so that cold gRPC connects have enough time to complete on retries.

gRPC

gRPC client's options

You can customize the gRPC client's behavior by setting options in config array

Example of using:

$config = [
    // ...
    'grpc' => [
        'opts' => [
            'grpc.max_receive_message_length' => 8*1024*1024,
            'grpc.default_compression_algorithm' => 2,
            'grpc.default_compression_level' => 2,
        ],
    ],
];
$ydb = new \YdbPlatform\Ydb\Ydb($config);

yandex-cloud/ydb-php-sdk 适用场景与选型建议

yandex-cloud/ydb-php-sdk 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 22.74k 次下载、GitHub Stars 达 38, 最近一次更新时间为 2021 年 04 月 18 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 yandex-cloud/ydb-php-sdk 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 yandex-cloud/ydb-php-sdk 我们能提供哪些服务?
定制开发 / 二次开发

基于 yandex-cloud/ydb-php-sdk 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 22.74k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 38
  • 点击次数: 7
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 38
  • Watchers: 11
  • Forks: 19
  • 开发语言: PHP

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2021-04-18