PHP langsys/langsys-php

기본 PHP SDK: 일반 PHP, 프레임워크, 워커, CLI 등 어떤 PHP 앱에서든 사용할 수 있는 하나의 클라이언트입니다. 코드에 작성한 문구는 조회 키이자 기본 언어의 기본값입니다. 키 파일도, 추출 단계도 필요 없습니다. 번역은 서버에서 이루어지므로 페이지가 이미 현지화된 상태로 전달됩니다.

백엔드 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분이면 둘 다 준비할 수 있습니다.

클라이언트

요청당 클라이언트 하나를 사용합니다. 클라이언트는 환경 변수에서 자격 증명을 읽고 로캘별 카탈로그를 캐시하므로, 페이지를 번역할 때 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()는 두 번째 인수로 로캘을, 세 번째 인수로 카테고리를 받습니다. 클라이언트의 현재 로캘을 사용하려면 로캘 자리에 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}을 사용하므로, 하나의 카탈로그가 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 중 하나입니다. 알고 있다면 항상 전달하세요. 작동 방식과 이 값이 필요한 문구를 찾는 방법 →

성별 인수 전달하기 소스 보기 ↗
// 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');
문서 및 학습 센터 검색