Lingara Lingara 說明文件 學習指南 API 函式庫 App 建立 網頁版
語言: 繁體中文

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

本頁封裝的內容