PHP
Questa pagina è tradotta dall'inglese. Se le due versioni differiscono, fa fede la pagina in inglese. Leggi la pagina in inglese
La libreria PHP è spinningcatstudios/lingara su Packagist. Richiede PHP 8.2 o successivo e comunica via HTTP tramite PSR-18, quindi funziona con Symfony HttpClient, Guzzle o un client tuo.
Come si usa
- Le chiamate sono sincrone. L’unico modo per annullare è smettere di leggere: esci dal
foreach, oppure chiamaclose()sullo stream. - Uno stream si legge con
foreach, una sola volta. Distingui ogni evento coninstanceof. - Gli errori implementano
Lingara\Exception\LingaraException. In un errore dell’API,errorCode()è il codice stabile egetCode()è lo stato HTTP;retryAfter()è un numero di secondi, oppurenull. - Scegli lo stack HTTP con l’argomento
http. Con Guzzle, gli stream richiedono cheallow_url_fopensia abilitato. Con un tuo client PSR-18, lo streaming e i timeout sono a tuo carico. - Con PHP-FPM ogni worker parte vuoto, quindi fornisci al client un
tokenCachePSR-16. Senza di esso, ogni worker scambia un proprio token, e il limite orario dell’endpoint dei token è condiviso da tutti.
Gli esempi qui sotto installano il pacchetto, creano un client, ricevono in streaming un elenco di vocaboli e gestiscono un errore.
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";
}
}