PHP
Halaman ini diterjemahkan daripada bahasa Inggeris. Jika kedua-duanya berbeza, halaman bahasa Inggeris adalah yang betul. Baca halaman bahasa Inggeris
Pustaka PHP ialah spinningcatstudios/lingara di Packagist. Ia memerlukan PHP 8.2 atau lebih baharu dan berkomunikasi melalui HTTP menerusi PSR-18, jadi ia berfungsi dengan Symfony HttpClient, Guzzle atau klien anda sendiri.
Cara ia digunakan
- Panggilan adalah segerak. Satu-satunya cara untuk membatalkan ialah berhenti membaca: keluar daripada
foreach, atau panggilclose()pada strim. - Strim dibaca dengan
foreach, sekali sahaja. Padankan setiap peristiwa denganinstanceof. - Ralat melaksanakan
Lingara\Exception\LingaraException. Pada ralat API,errorCode()ialah kod yang stabil dangetCode()ialah status HTTP;retryAfter()ialah bilangan saat, ataunull. - Pilih tindanan HTTP dengan argumen
http. Dengan Guzzle, strim memerlukanallow_url_fopendidayakan. Dengan klien PSR-18 anda sendiri, penstriman dan had masa perlu anda konfigurasikan sendiri. - Di bawah PHP-FPM setiap worker bermula kosong, jadi berikan klien sebuah
tokenCachePSR-16. Tanpanya, setiap worker menukar tokennya sendiri, dan had setiap jam endpoint token dikongsi oleh kesemuanya.
Contoh di bawah memasang pakej, mencipta klien, menstrim senarai perbendaharaan kata dan mengendalikan ralat.
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";
}
}