iwalkalone/translator

A class to manage translations and brings localization to your cli or web app

v1.8 2025-09-08 11:13 UTC

This package is auto-updated.

Last update: 2025-09-08 11:15:04 UTC


README

Description

A translator library using PHP gettext extension.

Install

Install with composer:

composer require iwalkalone/translator

Or a specific version:

composer require iwalkalone/translator ^1.7

How to use it

Example code to autodetect language using headers sent by client:

$available_languages = [
  'en_GB',
  'en_US',
  'ca_ES',
  'es_ES',
];
$default_language = 'ca_ES';
$path_to_translations = './locale';
$translator = new \iwalkalone\Translator($available_languages, $default_language, $path_to_translations);
$str = 'Hello!';
$translated = $translator->translate($str);

It also accepts placeholders. In next example, %username% is replaced for Mark after getting the translation.

$str = 'Hello %username%!';
$translated = $translator->translate($str, [
  'username' => 'Mark',
]);

You can disable language autodetection, specifying one:

$translator = new \iwalkalone\Translator($available_languages, $default_language, $path_to_translations, 'en_GB');

Be sure to generate all locales you want to use editing /etc/locale-gen and running locale-gen as root.

Compile translations:

It is as simple as:

$translator->compile();

By default it searches in ./I18N directory, but you can customize it:

$translator->compile("/path/to/translations");

If you want to compile it with JSON format:

$translator->compileJson("/path/to/translations", "/path/to/JSON/output");

Running tests:

install PHP libraries with composer

composer install

Run tests with codecept:

vendor/bin/codecept run