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 攏會家己換一个權杖,而且權杖端點的每點鐘上限是 in 攏總共用的。

下面的範例會安裝套件、建立用戶端、用串流提一份詞彙清單,閣處理錯誤。

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

這頁包的內容