PHP langsys/langsys-php

ベースとなる PHP SDK:プレーンな PHP、フレームワーク、ワーカー、CLI など、あらゆる PHP アプリで使える 1 つのクライアントです。コード内のフレーズが、そのまま検索キーであり、基準言語のデフォルトテキストにもなります。キーファイルも抽出作業も不要です。翻訳はサーバー側で行われるため、ページは最初からローカライズされた状態で届きます。

バックエンド SDK のため、このページにはブラウザ内プレイグラウンドはありません。ブラウザでは PHP を実行できないためです。Laravel をお使いですか?Laravel パッケージは、このクライアントを Blade ディレクティブ、ミドルウェア、ファサードでラップしています。詳細なリファレンスは README をご覧ください。

AI コーディングエージェントを使っていますか?次のプロンプトを渡してください
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.

インストール

composer require langsys/langsys-php

PHP 7.4 以降。curl、json、intl の各拡張機能が必要です。intl は、ロケールごとに複数形を処理し、数値や日付をフォーマットするために使われます。

.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

プロジェクトやキーをまだお持ちでない場合は、クイックスタートで 2 分ほどで両方とも用意できます。

クライアント

リクエストごとにクライアントを 1 つ使用します。認証情報は環境変数から読み込まれ、各ロケールのカタログがキャッシュされるため、ページを翻訳する際の API 呼び出しは多くても 1 回で済みます。

ソースを表示 ↗
<?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() は第 2 引数にロケール、第 3 引数にカテゴリを取ります。クライアントの現在のロケールを使うには、ロケールに null を渡します。

ソースを表示 ↗
// 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.

文中の値

プレースホルダーには、すべての Langsys SDK が保存する共通の形式である {name} を使用します。これにより、1 つのカタログが PHP バックエンドでも 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.

複数形

視聴 · 1:14 複数形の処理

文は単純な形で書いてください。Langsys が翻訳時に各ロケールの複数形を生成し、SDK が件数に合った形を表示します。

ソースを表示 ↗
// 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]);

Langsys が生成する複数形は、langsys/langsys-php 1.3.2 以降で PHP に反映されます。それより前のバージョンでは、1 を含むすべての数に対して複数形が表示されます。

性の一致

スペイン語、フランス語、ロシア語では、対象となる人物に合わせて {username} has been invited が語形変化します。Langsys は、複数形と同じように、翻訳時にこれらの分岐を生成します。引数の名前は変数名に _gender を付けたもので、値は male、female、other のいずれかです。分かる場合は必ず渡してください。仕組みと、対応が必要なフレーズの見つけ方 →

gender 引数を渡す ソースを表示 ↗
// 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'
]);

性別がわからない場合は、'other' を明示的に渡してください。これは中立のブランチです。渡し忘れても、SDK が自動的に other ブランチを使用するため、文は正しく表示されます。

カテゴリ

カテゴリがフレーズの適用範囲を定めるため、同じ文言でもコンテキストに応じて異なる翻訳にできます。

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

訪問者のロケール

独自のルーティングやユーザー設定から指定するか、クライアントにブラウザーのAccept-Languageヘッダーを読み取らせることができます。

ソースを表示 ↗
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'));

テンプレート内での使い方

小さなヘルパーを使うと、ビューに短い名前を付けられ、出力もエスケープされます。

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>

サーバー上でのトークン検出

書き込みキーを使うと、プロジェクトにとって未知のフレーズはすべてレンダリング時にキューに追加され、レスポンスの後に登録されます。訪問者にはすぐに基準言語のテキストが表示され、そのフレーズは次の訪問者のために翻訳されます。読み取り専用キーでは何も登録されませんが、動作に支障はありません。

ソースを表示 ↗
// 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],
]);

ページ全体

ページがすでに HTML 文字列になっていますか?head も含めて、一括で翻訳できます。

ソースを表示 ↗
// 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');

キャッシュ

ソースを表示 ↗
// 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');
ドキュメントとラーニングセンターを検索