PHP langsys/langsys-php

Podstawowy SDK dla PHP: jeden klient dla każdej aplikacji PHP — czystego PHP, frameworka, workera czy CLI. Fraza w Twoim kodzie jest zarówno kluczem wyszukiwania, jak i domyślnym tekstem w języku bazowym — bez pliku z kluczami i bez etapu ekstrakcji. Tłumaczenie odbywa się na serwerze, więc strona trafia do użytkownika już zlokalizowana.

To SDK backendowe, więc na tej stronie nie ma piaskownicy w przeglądarce — przeglądarka nie uruchomi PHP. Używasz Laravela? Pakiet Laravel opakowuje tego klienta dyrektywą Blade, middleware i fasadą. Pełna dokumentacja: README.

Korzystasz z agenta AI do kodowania? Daj mu ten 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.

Instalacja

composer require langsys/langsys-php

PHP 7.4 lub nowszy z rozszerzeniami curl, json i intl — to intl odpowiada za odmianę liczby mnogiej oraz formatowanie liczb i dat dla każdego języka.

.env
# 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

Nie masz jeszcze projektu ani kluczy? Szybki start zapewni Ci jedno i drugie w dwie minuty.

Klient

Jeden klient na żądanie. Pobiera dane uwierzytelniające ze zmiennych środowiskowych i buforuje katalog każdego języka, więc przetłumaczenie strony kosztuje co najwyżej jedno wywołanie API.

Zobacz źródło ↗
<?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');

Tłumacz

translate() przyjmuje wersję językową jako drugi argument, a kategorię jako trzeci. Przekaż null zamiast wersji językowej, aby użyć bieżącej wersji klienta.

Zobacz źródło ↗
// 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.

Wartości w zdaniu

Symbole zastępcze mają postać {name} — w tej samej formie zapisuje je każdy SDK Langsys, dzięki czemu jeden katalog jest renderowany identycznie przez backend PHP i frontend JS.

Zobacz źródło ↗
// 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.

Liczba mnoga

Obejrzyj · 1:14 Liczba mnoga

Zapisz zdanie w prostej formie: Langsys generuje formy liczby mnogiej dla każdego języka podczas tłumaczenia, a SDK renderuje wariant pasujący do Twojej liczby.

Zobacz źródło ↗
// 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]);

Formy liczby mnogiej generowane przez Langsys trafiają do PHP od wersji 1.3.2 pakietu langsys/langsys-php; starsze wersje renderują formę liczby mnogiej dla każdej liczby, także dla 1.

Zgodność rodzaju gramatycznego

W hiszpańskim, francuskim czy rosyjskim {username} has been invited odmienia się w zależności od osoby, której dotyczy. Langsys generuje te warianty podczas tłumaczenia — tak samo jak liczbę mnogą — a argument ma nazwę zmiennej z dopiskiem _gender: male, female lub other. Przekaż go zawsze, gdy go znasz. Jak to działa i jak znaleźć frazy, które tego potrzebują →

Przekazywanie argumentu płci Zobacz źródło ↗
// 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'
]);

Nie znasz płci? Przekaż jawnie 'other' — to gałąź neutralna. Jeśli jej mimo to zabraknie, SDK samo wybierze gałąź other, dzięki czemu zdanie nadal brzmi poprawnie.

Kategorie

Kategoria wyznacza zakres frazy, dzięki czemu te same słowa mogą być tłumaczone inaczej w różnych kontekstach.

// 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"

Ustawienia regionalne odwiedzającego

Ustaw je w własnym routingu lub w ustawieniach użytkownika albo pozwól klientowi odczytać nagłówek Accept-Language przeglądarki.

Zobacz źródło ↗
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'));

W Twoich szablonach

Mały helper nadaje widokom krótką nazwę i escapuje dane wyjściowe.

helpers.php
<?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>

Wykrywanie tokenów na serwerze

Przy kluczu z prawem zapisu każda fraza, której projekt jeszcze nie widział, trafia do kolejki podczas renderowania i jest rejestrowana po wysłaniu odpowiedzi — odwiedzający od razu widzi tekst w języku bazowym, a fraza zostaje przetłumaczona dla kolejnego. Przy kluczu tylko do odczytu nic nie jest rejestrowane i nic się nie psuje.

Zobacz źródło ↗
// 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],
]);

Całe strony

Masz już stronę jako ciąg HTML? Przetłumacz ją jednym przebiegiem, razem z sekcją head.

Zobacz źródło ↗
// 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');

Buforowanie

Zobacz źródło ↗
// 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');
Szukaj w dokumentacji i Centrum nauki