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에서는 모든 워커가 빈 상태로 시작하므로, 클라이언트에 PSR-16
tokenCache를 제공하세요. 없으면 각 워커가 자기 토큰을 따로 교환하고, 토큰 엔드포인트의 시간당 한도를 모든 워커가 나눠 쓰게 됩니다.
아래 샘플은 패키지를 설치하고, 클라이언트를 만들고, 어휘 목록을 스트리밍하고, 오류를 처리합니다.
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";
}
}