PHP code example of dschuppelius / php-translation-toolkit

1. Go to this page and download the library: Download dschuppelius/php-translation-toolkit library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dschuppelius / php-translation-toolkit example snippets


use TranslationToolkit\{TranslationRegistry, TranslationService};
use TranslationToolkit\Providers\DeepLProvider;

$service = new TranslationService(
    provider: new DeepLProvider($apiKey),
    cache: $myDbCache,            // TranslationCacheInterface, optional
    usageListener: $myUsageLog,   // TranslationUsageListenerInterface, optional
    defaultTargetLang: 'de',
);

// Direkt …
$result = $service->translate('Привет мир, как дела?');
$result->text;        // "Hallo Welt, wie geht es?"
$result->fromCache;   // false beim ersten, true beim zweiten Aufruf
$result->charCount;   // Berechnungsgrundlage (Zeichen des Quelltexts)

// … oder über die Registry (Host-Bootstrap setzt, Bibliothekscode liest)
TranslationRegistry::setService($service);
if (TranslationRegistry::isAvailable() && TranslationService::needsTranslation($text)) {
    $text = TranslationRegistry::getService()->translate($text)->text;
}

use TranslationToolkit\Entities\TranslateOptions;
use TranslationToolkit\Providers\{CompositeProvider, DeepLProvider, LibreTranslateProvider};

// Viele Texte: Cache-Treffer einzeln, Misses gebündelt (DeepL 50/Azure 100 je Request)
$results = $service->translateMany($verwendungszwecke, 'de', 'ru');

// Host-Defaults (z.B. Mandanten-Glossar) greifen, wenn der Aufrufer nichts übergibt
$service = new TranslationService($provider, defaultOptions: new TranslateOptions(glossary: $mandantenGlossar));

// Fallback-Kette: self-hosted zuerst, Cloud als Reserve
$provider = new CompositeProvider(new LibreTranslateProvider($url), new DeepLProvider($key));

use TranslationToolkit\Entities\{GlossaryEntry, TranslateOptions};
use TranslationToolkit\Enums\{Formality, TextFormat};

$result = $service->translate('The invoice date is due', 'de', 'en', new TranslateOptions(
    format: TextFormat::Html,        // Markup schonen
    formality: Formality::More,      // förmlichere Zielsprache (DeepL)
    glossary: [new GlossaryEntry('invoice date', 'Belegdatum')],
));

$result->deterministicTerminology;   // true, wenn die Begriffe erzwungen wurden

new DeepLProvider(
    apiKey: $apiKey,
    glossaryIdStore: $myPersistentStore,   // GlossaryIdStoreInterface
    glossaryName: 'meine-app-mandant-42',
);