PHP langsys/langsys-php
L'SDK PHP di base: un unico client per qualsiasi app PHP — PHP puro, un framework, un worker o una CLI. La frase nel tuo codice è allo stesso tempo la chiave di ricerca e il valore predefinito nella lingua di base — nessun file di chiavi, nessun passaggio di estrazione. La traduzione avviene sul server, quindi la pagina arriva già localizzata.
SDK backend, quindi in questa pagina non c'è un playground nel browser: il browser non può eseguire PHP. Usi Laravel? Il pacchetto Laravel incapsula questo client con una direttiva Blade, un middleware e una facade. Riferimento completo: il README.
Usi un agente di programmazione basato su IA? Dagli questo prompt
Add Langsys translation to this PHP app.
1. Read https://docs.langsys.dev/llms.txt, then follow
https://docs.langsys.dev/learn/sdk/php/ for the install and setup.
2. The English text in the code is the translation key. Wrap user-facing
strings as they are: no keys file, no extraction step, and no
hand-written plural or gender branches (Langsys generates those).
3. Read the Langsys project id and API key from environment variables.
The write key is for development and servers only; anything shipped
to the browser gets the read-only key.
4. Keep brand names and user-generated content out of translation. Installa
composer require langsys/langsys-php PHP 7.4 o versioni successive, con le estensioni curl, json e intl: intl è l'estensione che gestisce i plurali e formatta numeri e date per ogni locale.
# A server can hold a WRITE key — it never reaches visitors. A write key is
# what lets phrases your pages use for the first time register themselves.
LANGSYS_API_KEY=your-api-key
LANGSYS_PROJECT_ID=your-project-id Non hai ancora un progetto o le chiavi? La guida rapida ti dà entrambi in due minuti.
Il client
Un client per richiesta. Legge le credenziali dall'ambiente e mette in cache il catalogo di ogni locale, quindi tradurre una pagina costa al massimo una chiamata API.
<?php
require 'vendor/autoload.php';
use LangsysSDKClient;
// Reads LANGSYS_API_KEY and LANGSYS_PROJECT_ID from the environment.
$langsys = new Client();
$langsys->setLocale('es-es'); Translate
translate() accetta la lingua come secondo argomento e la categoria come terzo. Passa null come lingua per usare quella corrente del client.
// translate($phrase, $locale, $category, $contentBlockId, $params)
echo $langsys->translate('Order confirmed', null, 'Checkout'); // current locale
echo $langsys->translate('Order confirmed', 'fr-fr', 'Checkout'); // an explicit one
// A phrase the project doesn't have yet renders as written — never blank. Valori in una frase
I segnaposto usano {name}, la stessa forma che memorizza ogni SDK Langsys, così un unico catalogo viene renderizzato in modo identico da un backend PHP e da un frontend JS.
// Pass values as params, never build the string yourself.
echo $langsys->translate('Hello, {name}!', null, 'Greetings', null, ['name' => $user->name]);
// sprintf('Hello, %s!', $name) would register "Hello, Sarah!", "Hello, Ahmed!", …
// — one catalog entry per value, billed as words, and impossible to undo. Plurali
Scrivi la frase in forma semplice: Langsys genera le forme plurali di ogni lingua durante la traduzione e l'SDK mostra la variante corrispondente al tuo conteggio.
// Written flat. Langsys generates each locale's plural forms during
// translation and the SDK picks the branch that matches the count.
echo $langsys->translate('You have {count} new messages.', null, 'Inbox', null, ['count' => $count]); Le forme plurali generate da Langsys arrivano in PHP a partire da langsys/langsys-php 1.3.2; le versioni precedenti usano la forma plurale per qualsiasi conteggio, incluso 1.
Concordanza di genere
Spagnolo, francese o russo flettono {username} has been invited in base alla persona a cui ci si riferisce. Langsys genera queste varianti durante la traduzione — nello stesso modo in cui genera i plurali — e l'argomento prende il nome dalla variabile, con _gender aggiunto in coda: male, female oppure other. Passalo ogni volta che lo conosci. Come funziona e come trovare le frasi che ne hanno bisogno →
// Pass the agreement argument alongside the value it inflects.
echo $langsys->translate('{username} has been invited', null, 'Team', null, [
'username' => $user->name,
'username_gender' => $user->gender, // 'male' | 'female' | 'other'
]); Non conosci il genere? Passa 'other' in modo esplicito: è il ramo neutro. Se manca comunque, l'SDK usa per te il ramo other, così la frase si legge comunque correttamente.
Categorie
La categoria definisce l'ambito di una frase, quindi le stesse parole possono essere tradotte in modo diverso in contesti diversi.
// Same word, two meanings — the category disambiguates.
echo $langsys->translate('Home', null, 'Main Menu'); // es: "Inicio"
echo $langsys->translate('Home', null, 'Home repairs'); // es: "Casa" La lingua del visitatore
Impostala dal tuo routing o dalle impostazioni dell'utente, oppure lascia che il client legga l'header Accept-Language del browser.
use LangsysSDKLocaleLocaleDetector;
// Explicit, from your own routing or the user's settings:
$langsys->setLocale('pt-br');
// Or from the browser: without setLocale(), getLocale() reads Accept-Language
// and falls back to the project's base locale.
$locale = $langsys->getLocale();
// The same detection, from a header your framework hands you:
$locale = LocaleDetector::fromAcceptLanguage($request->getHeaderLine('Accept-Language')); Nei tuoi template
Un piccolo helper dà alle tue viste un nome breve ed esegue l'escape dell'output.
<?php
// helpers.php — one client per request, one short name in your templates.
use LangsysSDKClient;
function t(string $phrase, string $category, array $params = []): string
{
static $langsys = null;
$langsys ??= (new Client())->setLocale($_SESSION['locale'] ?? 'en-us');
return htmlspecialchars($langsys->translate($phrase, null, $category, null, $params));
}
// In a template:
// <h1><?= t('Welcome to our store', 'Home') ?></h1> Rilevamento dei token sul server
Con una chiave di scrittura, ogni frase che il progetto non ha ancora visto viene messa in coda durante il rendering e registrata dopo la risposta: il visitatore vede subito il testo nella tua lingua di base, e la frase viene tradotta per il successivo. Con una chiave di sola lettura non viene registrato nulla e non si rompe nulla.
// With a write key, translate() queues every phrase the project doesn't have
// and sends them after the response, from a shutdown handler. Nothing to call.
// With a read key the queue is simply dropped — no errors.
// Or register up front, e.g. from a deploy script:
$langsys->registerPhrases([
['phrase' => 'Order confirmed', 'category' => 'Checkout'],
['phrase' => 'Copyright 2026', 'category' => 'Footer', 'translatable' => false],
]); Pagine intere
Hai già la pagina come stringa HTML? Traducila in un solo passaggio, head compreso.
// An HTML page you already have as a string: <title>, meta and OpenGraph
// tags, and the body — phrases and content blocks — in one pass.
ob_start();
// … your app renders the page …
$html = ob_get_clean();
echo $langsys->setLocale('es-es')->translatePage($html, 'Home'); Caching
// Catalogs are cached for an hour (a file cache by default; Redis or none
// via LANGSYS_CACHE_DRIVER). After editing translations in the dashboard:
$langsys->clearCache('es-es');