PHP
このページは英語から翻訳されています。内容に相違がある場合は、英語のページが正しい内容です。 英語のページを読む
PHP ライブラリは Packagist の spinningcatstudios/lingara です。PHP 8.2 以降が必要で、HTTP 通信は PSR-18 を介して行うため、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 では各ワーカーが空の状態で起動するため、クライアントに PSR-16 の
tokenCacheを渡してください。これがないと各ワーカーが個別にトークンを交換し、トークンエンドポイントの 1 時間あたりの上限をすべてのワーカーで共有することになります。
以下のサンプルでは、パッケージのインストール、クライアントの作成、語彙リストのストリーミング、エラー処理を行います。
PHP
composer require spinningcatstudios/lingara:0.1.0-alpha.6PHP
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";
}
}