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.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";
}
}