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

這頁包裝个內容