PHP
Esta página é uma tradução do inglês. Se as duas diferirem, a página em inglês é a correta. Ler a página em inglês
A biblioteca PHP é spinningcatstudios/lingara no Packagist. Requer PHP 8.2 ou posterior e comunica por HTTP através de PSR-18, pelo que funciona com Symfony HttpClient, Guzzle ou um cliente seu.
Como se utiliza
- As chamadas são síncronas. A única forma de cancelar é deixar de ler: saia do
foreach, ou chameclose()no stream. - Um stream lê-se com
foreach, uma única vez. Distinga cada evento cominstanceof. - Os erros implementam
Lingara\Exception\LingaraException. Num erro da API,errorCode()é o código estável egetCode()é o estado HTTP;retryAfter()é um número de segundos, ounull. - Escolha a pilha HTTP com o argumento
http. Com Guzzle, os streams precisam deallow_url_fopenativado. Com um cliente PSR-18 seu, o streaming e os tempos limite ficam ao seu cuidado. - Com PHP-FPM, cada worker começa vazio, por isso dê ao cliente um
tokenCachePSR-16. Sem ele, cada worker troca o seu próprio token, e o limite horário do endpoint de tokens é partilhado por todos.
Os exemplos abaixo instalam o pacote, criam um cliente, recebem em stream uma lista de vocabulário e tratam um erro.
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";
}
}