Lingara Lingara 文档 学习指南 API 库 应用 构建 网页版
语言: 中文简体

PHP

本页译自英文。如两者有出入,以英文页面为准。 阅读英文页面

PHP 库是 Packagist 上的 spinningcatstudios/lingara。它需要 PHP 8.2 或更高版本,通过 PSR-18 进行 HTTP 通信,因此可以配合 Symfony HttpClient、Guzzle 或你自己的客户端使用。

用法一览

  • 调用是同步的。唯一的取消方式是停止读取:跳出 foreach,或者在流上调用 close()。
  • 流用 foreach 读取,只能读取一次。用 instanceof 匹配每个事件。
  • 错误实现 Lingara\Exception\LingaraException。对于 API 错误,errorCode() 是稳定的错误代码,getCode() 是 HTTP 状态码;retryAfter() 是秒数,或者为 null。
  • 用 http 参数选择 HTTP 栈。使用 Guzzle 时,流需要启用 allow_url_fopen。使用你自己的 PSR-18 客户端时,流和超时都需要你自行配置。
  • 在 PHP-FPM 下,每个 worker 启动时都是空的,所以请给客户端提供一个 PSR-16 tokenCache。如果没有,每个 worker 都会各自交换令牌,而令牌端点的每小时限额由它们全部共享。

下面的示例会安装包、创建客户端、以流的方式获取词汇列表并处理错误。

PHP

composer require spinningcatstudios/lingara:0.1.0-alpha.6

PHP

use Lingara\Client;

$client = new Client(clientId: $clientId, clientSecret: $clientSecret);

PHP

use Lingara\Model\VocabRequest;
use Lingara\Stream\GenerateVocabularyEvent;

$request = new VocabRequest(['level' => 2, 'source_lang' => 'en', 'target_lang' => 'zh', 'count' => 8]);
foreach ($client->generateVocabulary($request) as $event) {
    if ($event instanceof GenerateVocabularyEvent\Item) {
        echo $event->data->getWord(), ': ', $event->data->getTranslation(), "\n";
    }
}

PHP

use Lingara\Exception\ApiException;
use Lingara\Exception\LingaraException;
use Lingara\Exception\MaintenanceException;
use Lingara\Exception\OAuthException;
use Lingara\Exception\TransportException;

try {
    $client->getUsage();
} catch (LingaraException $e) {
    if ($e instanceof ApiException) {
        // A refusal from the API: status, errorCode (stable) and message (localised).
        echo $e->status(), ' ', $e->errorCode(), ': ', $e->getMessage(), "\n";
        echo 'retry after: ', $e->retryAfter() ?? 'not given', "\n";
    } elseif ($e instanceof OAuthException) {
        // The token endpoint refused the credentials or the scopes.
        echo $e->status(), ' ', $e->error(), ': ', $e->description(), "\n";
    } elseif ($e instanceof MaintenanceException) {
        echo 'under maintenance; retry after: ', $e->retryAfter() ?? 'not given', "\n";
    } elseif ($e instanceof TransportException) {
        // No usable answer: connect, tls, reset, timeout, and so on.
        echo 'transport: ', $e->kind()->value, "\n";
    }
}

本页封装的内容