PHPackages                             locomotivemtl/charcoal-translator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Localization &amp; i18n](/categories/localization)
4. /
5. locomotivemtl/charcoal-translator

ActiveLibrary[Localization &amp; i18n](/categories/localization)

locomotivemtl/charcoal-translator
=================================

Charcoal service provider for translating messages and managing locales.

0.3.7.1(6y ago)018.3k11MITPHPPHP &gt;=5.6.0 || &gt;=7.0CI failing

Since Feb 7Pushed 4y ago13 watchersCompare

[ Source](https://github.com/locomotivemtl/charcoal-translator)[ Packagist](https://packagist.org/packages/locomotivemtl/charcoal-translator)[ Docs](https://locomotivemtl.github.io/charcoal-translator/)[ RSS](/packages/locomotivemtl-charcoal-translator/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (10)Dependencies (8)Versions (28)Used By (11)

Charcoal Translator
===================

[](#charcoal-translator)

[![License](https://camo.githubusercontent.com/51247668ac986775bbca01a42c3a1ff285ef12fe7867dd31c5a4d653519abfe1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6c6f636f6d6f746976656d746c2f63686172636f616c2d7472616e736c61746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/locomotivemtl/charcoal-translator)[![Latest Stable Version](https://camo.githubusercontent.com/e913dd7e367e7447e403eda251c41428196159a1b1f5e9a2b585ba2d6a83a680/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c6f636f6d6f746976656d746c2f63686172636f616c2d7472616e736c61746f722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/locomotivemtl/charcoal-translator)[![Code Quality](https://camo.githubusercontent.com/73cddb0cd71a9e21db791edb75ce7df329f603b2afea566d3665ae337337f2d4/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f6c6f636f6d6f746976656d746c2f63686172636f616c2d7472616e736c61746f722e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/locomotivemtl/charcoal-translator/)[![Coverage Status](https://camo.githubusercontent.com/b470c8bb47efd5cceeccef75ab142e7ccad71f03ec95532f4ae488b2bac7f4e9/68747470733a2f2f696d672e736869656c64732e696f2f636f766572616c6c732f6c6f636f6d6f746976656d746c2f63686172636f616c2d7472616e736c61746f722e7376673f7374796c653d666c61742d737175617265)](https://coveralls.io/github/locomotivemtl/charcoal-translator)[![SensioLabs Insight](https://camo.githubusercontent.com/a628c69f50c6355f2f8b4d6da23a785578e0271e619ddb30cc1a3c6c873c1ede/68747470733a2f2f696d672e736869656c64732e696f2f73656e73696f6c6162732f692f32373538633832302d653733612d346430652d623734362d3535326133653361393266612e7376673f7374796c653d666c61742d737175617265)](https://insight.sensiolabs.com/projects/2758c820-e73a-4d0e-b746-552a3e3a92fa)[![Build Status](https://camo.githubusercontent.com/e6d709ce8a0f2dd5f3c21a629a20ab48abd97ba7e21911ed17f857f41aac261a/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f6c6f636f6d6f746976656d746c2f63686172636f616c2d7472616e736c61746f722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/locomotivemtl/charcoal-translator)

A [Charcoal](https://packagist.org/packages/locomotivemtl/charcoal-app) service provider for the [Symfony Translation component](https://packagist.org/packages/symfony/translation).

Provides internationalization (I18N) tools for translating messages and managing locales in multilingual applications.

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
    - [Dependencies](#dependencies)
- [Features](#features)
    - [The Translation Object](#the-translation-object)
    - [The Translator Service](#the-translator-service)
    - [The Locales Manager](#the-locales-manager)
    - [The Parser Script](#the-parser-script)
- [Service Provider](#service-provider)
    - [Parameters](#parameters)
    - [Services](#services)
- [Configuration](#configuration)
- [Middleware](#middleware)
- [Helpers](#helpers)
    - [TranslatorAwareTrait](#translatorawaretrait)
- [Development](#development)
    - [Development dependencies](#development-dependencies)
    - [Continuous Integration](#continuous-integration)
    - [Coding Style](#coding-style)
- [Credits](#credits)
- [License](#license)

Installation
------------

[](#installation)

1. The preferred (and only supported) method is with Composer:

    ```
    ★ composer require locomotivemtl/charcoal-translator
    ```
2. Add the service provider and configure the default translator / locale services via the application configset:

    ```
    "service_providers": {
        "charcoal/translator/service-provider/translator": {}
    },

    "translator": {
        // …
    },

    "locales": {
        // …
    }
    ```

    or via the service container:

    ```
    $container->register(new \Charcoal\Translator\ServiceProvider\TranslatorServiceProvider());

    $container['translator/config'] = new \Charcoal\Translator\TranslatorConfig([
        // …
    ]);

    $container['locales/config'] = new \Charcoal\Translator\LocalesConfig([
        // …
    ]);
    ```

If you are using [*locomotivemtl/charcoal-app*](https://packagist.org/packages/locomotivemtl/charcoal-app), the \[`TranslatorServiceProvider`\]\[translator-provider\] is automatically registered by the [`AppServiceProvider`](https://github.com/locomotivemtl/charcoal-app/blob/0.8.0/src/Charcoal/App/ServiceProvider/AppServiceProvider.php).

### Dependencies

[](#dependencies)

#### Required

[](#required)

- [**PHP 5.6+**](https://php.net): *PHP 7* is recommended.
- [**symfony/translation**](https://packagist.org/packages/symfony/translation): Translation component which Charcoal's translator service extends.
- [**pimple/pimple**](https://packagist.org/packages/pimple/pimple): PSR-11 compliant service container and provider library.
- [**locomotivemtl/charcoal-config**](https://packagist.org/packages/locomotivemtl/charcoal-config): For configuring the translator service and locales.

#### PSR

[](#psr)

- [**PSR-7**](https://www.php-fig.org/psr/psr-7/): Common interface for HTTP messages. Followed by [`LanguageMiddleware`](src/Charcoal/Translator/Middleware/LanguageMiddleware.php).
- [**PSR-11**](https://www.php-fig.org/psr/psr-11/): Common interface for dependency containers. Fulfilled by Pimple.

### Dependents

[](#dependents)

- [**locomotivemtl/charcoal-admin**](https://packagist.org/packages/locomotivemtl/charcoal-admin): Admin interface for Charcoal applications.
- [**locomotivemtl/charcoal-app**](https://packagist.org/packages/locomotivemtl/charcoal-app): PSR-7 compliant framework for web applications.
    For resolving the current locale via the [`LanguageMiddleware`](src/Charcoal/Translator/Middleware/LanguageMiddleware.php).
- [**locomotivemtl/charcoal-cms**](https://packagist.org/packages/locomotivemtl/charcoal-cms): Pre-designed models and basic utilities for content management (pages, news, events).
    For supporting multilingual model properties and localizing model descriptors.
- [**locomotivemtl/charcoal-property**](https://packagist.org/packages/locomotivemtl/charcoal-property): Model property values and metadata.
    For supporting multilingual values and localizing property descriptors.

Features
--------

[](#features)

### The Translation Object

[](#the-translation-object)

[`Charcoal\Translator\Translation`](src/Charcoal/Translator/Translation.php)

The *Translation Object* holds the translation data for a given string in all available languages / locales.

```
// Get a translation object from the Translator
$translation = $container['translator']->translation([
    'en' => 'Hello World',
    'fr' => 'Bonjour'
]);

// If cast to string, the default language will be used.
echo $translation;

// Use ArrayAccess to get (or set) a translated value.
echo $translation['fr'];
$translation['fr'] => 'Bonjour le monde';

// To loop through all translations:
foreach ($translation->data() as $lang => $translatedValue) {
    // ...
}
```

### The Translator Service

[](#the-translator-service)

[`Charcoal\Translator\Translator`](src/Charcoal/Translator/Translator.php)

Charcoal's *Translator* extends Symfony's [`Translator`](https://api.symfony.com/master/Symfony/Component/Translation/Translator.html) to also provide two new translation methods (`translation($val)` and `translator($val)`) which can both accept mixed arguments to return either a *Translation* object, in the case of `translation()` or a *string*, in the case of `translate($val)`.

### The Locales Manager

[](#the-locales-manager)

[`Charcoal\Translator\LocalesManager`](src/Charcoal/Translator/LocalesManager.php)

The *Locales Manager* is used to manage available locales / languages and keep track of current language.

### The Parser Script

[](#the-parser-script)

[`Charcoal\Translator\Script\TranslationParserScript`](src/Charcoal/Translator/Script/TranslationParserScript.php)

The *Parser Script* is used to scrape files that contain translatable content. Add the following route to your application configuration:

```
"scripts": {
    "charcoal/translator/parse": {
        "ident": "charcoal/translator/script/translation-parser"
    }
}
```

Service Provider
----------------

[](#service-provider)

The [`TranslatorServiceProvider`](src/Charcoal/Translator/ServiceProvider/TranslatorServiceProvider.php) provides services and options for translating your application into different languages.

### Parameters

[](#parameters)

- **locales/config**: Configuration object for defining the available languages, fallbacks, and defaults.
- **locales/default-language**: Default language of the application, optionally the navigator's preferred language.
- **locales/browser-language**: Accepted language from the navigator.
- **locales/fallback-languages**: List of fallback language codes for the translator.
- **locales/available-languages**: List of language codes from the available locales.
- **locales/languages**: List of available language structures of the application.
- **translator/config**: Configuration object for translation service, message catalogs, and catalog loaders.
- **translator/translations**: Dictionary of additional translations grouped by domain and locale.

### Services

[](#services)

- **locales/manager**: An instance of [`LocalesManager`](src/Charcoal/Translator/LocalesManager.php), used for handling available languages, their definitions, the default language, and tracks the current language.
- **translator**: An instance of [`Translator`](src/Charcoal/Translator/Translator.php), that is used for translation.
- **translator/message-selector**: An instance of [`Symfony\Component\Translation\MessageSelector`](https://api.symfony.com/master/Symfony/Component/Translation/MessageSelector.html).
- **translator/loader/\***: Instances of the translation [`Symfony\Component\Translation\Loader\LoaderInterface`](https://api.symfony.com/master/Symfony/Component/Translation/Loader/LoaderInterface.html).

Configuration
-------------

[](#configuration)

Here is an example of configuration:

```
"locales": {
    "languages": {
        "de": {},
        "en": {},
        "es": {
            "active": false
        },
        "fr": {}
    },
    "default_language": "fr",
    "fallback_languages": [
        "en",
        "fr"
    ],
    "auto_detect": true
},
"translator": {
    "loaders": [
        "xliff",
        "json",
        "php"
    ],
    "paths": [
        "translations/",
        "vendor/locomotivemtl/charcoal-app/translations/"
    ],
    "debug": false,
    "cache_dir": "cache/translation/",
    "translations": {
        "messages": {
            "de": {
                "hello": "Hallo {{ name }}",
                "goodbye": "Auf Wiedersehen!"
            },
            "en": {
                "hello": "Hello {{ name }}",
                "goodbye": "Goodbye!"
            },
            "es": {
                "hello": "Hallo {{ name }}",
                "goodbye": "Adios!"
            },
            "fr": {
                "hello": "Bonjour {{ name }}",
                "goodbye": "Au revoir!"
            }
        },
        "admin": {
            "fr": {
                "Save": "Enregistrer"
            }
        }
    }
}
```

Middleware
----------

[](#middleware)

The [`LanguageMiddleware`](src/Charcoal/Translator/Middleware/LanguageMiddleware.php) is available for PSR-7 applications that support middleware. The middleware detects the preferred language using the `Accept-Language` HTTP header, the URI path, query string, or host.

If you are using [*locomotivemtl/charcoal-app*](https://packagist.org/packages/locomotivemtl/charcoal-app), you can add the middleware via the application configset:

```
"middlewares": {
    "charcoal/translator/middleware/language": {
        "active": true,
        "use_params": true,
        "param_key": "hl"
    }
}
```

Otherwise, with [Slim](https://packagist.org/packages/slim/slim), for example:

```
$app = new \Slim\App();

// Register middleware
$app->add(new \Charcoal\Translator\Middleware\LanguageMiddleware([
    'default_language' => 'fr',
    'use_params'       => true,
    'param_key'        => 'hl',
]));
```

The middleware comes with a set of default options which can be individually overridden.

SettingTypeDefaultDescription**active**`boolean``FALSE`Whether to enable or disable the middleware ([*locomotivemtl/charcoal-app*](https://packagist.org/packages/locomotivemtl/charcoal-app) only).**default\_language**`string``null`The default language to use if no other languages is choosen.**browser\_language**`string``null`The client's preferred language (`Accept-Language`).**use\_browser**`boolean``true`Whether to use `browser_language` as the default language.**use\_path**`boolean``true`Whether to lookup the HTTP request's URI path for a language code.**excluded\_path**`stringarray``^/admin\b`**path\_regexp**`stringarray``^/([a-z]{2})\b`**use\_params**`boolean``false`Whether to lookup the HTTP request's URI query string for a language code.**param\_key**`stringarray``current_language`**use\_session**`boolean``true`Whether to lookup the client's PHP session for a preferred language.**session\_key**`stringarray``current_language`**use\_host**`boolean``false`Whether to lookup the server host for a language code.**host\_map**`stringarray``[]`**set\_locale**`boolean``true`Whether to set the environment's locale.Helpers
-------

[](#helpers)

### TranslatorAwareTrait

[](#translatorawaretrait)

[`Charcoal\Translator\TranslatorAwareTrait`](src/Charcoal/Translator/TranslatorAwareTrait.php)

The `TranslatorAwareTrait` is offered as convenience to avoid duplicate / boilerplate code. It simply sets and gets a `Translator` service property.

Set with `setTranslator()` and get with `translator()`. Both are protected method. (This trait has no public interface.)

Development
-----------

[](#development)

To install the development environment:

```
★ composer install --prefer-source
```

To run the scripts (phplint, phpcs and phpunit):

```
★ composer tests
```

### API Documentation

[](#api-documentation)

- The auto-generated `phpDocumentor` API documentation is available at:

- The auto-generated `apigen` API documentation is available at:
    [https://codedoc.pub/locomotivemtl/charcoal-translator/master/](https://codedoc.pub/locomotivemtl/charcoal-translator/master/index.html)

### Development Dependencies

[](#development-dependencies)

- [php-coveralls/php-coveralls](https://packagist.org/packages/php-coveralls/php-coveralls)
- [phpunit/phpunit](https://packagist.org/packages/phpunit/phpunit)
- [squizlabs/php\_codesniffer](https://packagist.org/packages/squizlabs/php_codesniffer)

### Coding Style

[](#coding-style)

The charcoal-translator module follows the Charcoal coding-style:

- [*PSR-1*](https://www.php-fig.org/psr/psr-1/)
- [*PSR-2*](https://www.php-fig.org/psr/psr-2/)
- [*PSR-4*](https://www.php-fig.org/psr/psr-4/), autoloading is therefore provided by *Composer*.
- [*phpDocumentor*](http://phpdoc.org/) comments.
- [phpcs.xml.dist](phpcs.xml.dist) and [.editorconfig](.editorconfig) for coding standards.

> Coding style validation / enforcement can be performed with `composer phpcs`. An auto-fixer is also available with `composer phpcbf`.

Credits
-------

[](#credits)

- [Mathieu Ducharme](https://github.com/mducharme)
- [Chauncey McAskill](https://github.com/mcaskill)
- [Benjamin Roch](https://github.com/beneroch)
- [Locomotive](https://locomotive.ca/)

License
-------

[](#license)

Charcoal is licensed under the MIT license. See [LICENSE](LICENSE) for details.

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity22

Limited adoption so far

Community26

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 60.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~91 days

Recently: every ~361 days

Total

22

Last Release

1468d ago

PHP version history (2 changes)0.1PHP &gt;=5.6.0

0.3.3PHP &gt;=5.6.0 || &gt;=7.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/cfb071c0ff7ce9500c528a003a2c53124248debc3e5bf367c17f89f5e6136125?d=identicon)[mducharme](/maintainers/mducharme)

![](https://www.gravatar.com/avatar/0a4f39523b4b2837562ba0848a0327b8d340118d1ba87cb0f5d59b1d5cb6beba?d=identicon)[mcaskill](/maintainers/mcaskill)

---

Top Contributors

[![mcaskill](https://avatars.githubusercontent.com/u/29353?v=4)](https://github.com/mcaskill "mcaskill (52 commits)")[![mducharme](https://avatars.githubusercontent.com/u/12157?v=4)](https://github.com/mducharme "mducharme (21 commits)")[![JoelAlphonso](https://avatars.githubusercontent.com/u/10762266?v=4)](https://github.com/JoelAlphonso "JoelAlphonso (6 commits)")[![BeneRoch](https://avatars.githubusercontent.com/u/3017380?v=4)](https://github.com/BeneRoch "BeneRoch (4 commits)")[![dominiclord](https://avatars.githubusercontent.com/u/1775204?v=4)](https://github.com/dominiclord "dominiclord (3 commits)")

---

Tags

charcoali18nintll10ntranslationtranslatori18nl10ntranslationtranslatorcharcoalg11n

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/locomotivemtl-charcoal-translator/health.svg)

```
[![Health](https://phpackages.com/badges/locomotivemtl-charcoal-translator/health.svg)](https://phpackages.com/packages/locomotivemtl-charcoal-translator)
```

###  Alternatives

[lexik/translation-bundle

This bundle allows to import translation files content into the database and provide a GUI to edit translations.

4362.7M19](/packages/lexik-translation-bundle)[aura/intl

The Aura Intl package provides internationalization tools, specifically message translation.

898.3M4](/packages/aura-intl)[mediawiki/translate

The only standard solution to translate any kind of text with an avant-garde web interface within MediaWiki, including your documentation and software

457.9k](/packages/mediawiki-translate)[jrmajor/fluent

Fluent localization system for PHP

2716.9k5](/packages/jrmajor-fluent)[loco/loco

Loco SDK for PHP, including REST API client

19626.8k4](/packages/loco-loco)[inpsyde/multilingual-press

Simply THE multisite-based free open source plugin for your multilingual websites.

2414.0k1](/packages/inpsyde-multilingual-press)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
