PHP
Cette page est traduite de l'anglais. En cas de différence, la page anglaise fait foi. Lire la page en anglais
La bibliothèque PHP est spinningcatstudios/lingara sur Packagist. Elle nécessite PHP 8.2 ou version ultérieure et communique en HTTP via PSR-18, si bien qu’elle fonctionne avec Symfony HttpClient, Guzzle ou un client de votre choix.
À quoi elle ressemble
- Les appels sont synchrones. La seule façon d’annuler est d’arrêter de lire : quittez le
foreach, ou appelezclose()sur le flux. - Un flux se lit avec
foreach, une seule fois. Identifiez chaque événement avecinstanceof. - Les erreurs implémentent
Lingara\Exception\LingaraException. Pour une erreur d’API,errorCode()est le code stable etgetCode()le statut HTTP ;retryAfter()est un nombre de secondes, ounull. - Choisissez la pile HTTP avec l’argument
http. Avec Guzzle, les flux nécessitent queallow_url_fopensoit activé. Avec votre propre client PSR-18, la diffusion en flux et les délais d’expiration sont à votre charge. - Sous PHP-FPM, chaque worker démarre à vide : donnez donc au client un
tokenCachePSR-16. Sans cela, chaque worker échange son propre jeton, et la limite horaire du point de terminaison de jetons est partagée entre tous.
Les exemples ci-dessous installent le paquet, créent un client, diffusent une liste de vocabulaire et gèrent une erreur.
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";
}
}