PHPackages                             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. charcoal/translator

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

charcoal/translator
===================

Charcoal service provider for translating messages and managing locales.

v5.0.0(2y ago)010011MITPHPPHP ^7.4 || ^8.0

Since Feb 7Pushed 2y ago2 watchersCompare

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

READMEChangelogDependencies (9)Versions (52)Used By (11)

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

[](#charcoal-translator)

The Transator package provides tools to internationalize Web applications with support for multilingual data and an integration with [Symfony's Translation component](https://github.com/symfony/translation).

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

[](#installation)

```
composer require charcoal/translator
```

For Charcoal projects, the service provider can be registered from your configuration file:

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

Overview
--------

[](#overview)

### 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/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 [charcoal/app](https://github.com/charcoalphp/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://github.com/slimphp/Slim), for example:

```
use Charcoal\Translator\Middleware\LanguageMiddleware;
use Slim\App;

$app = new App();

// Register middleware
$app->add(new 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 ([charcoal/app](https://github.com/charcoalphp/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.)

Resources
---------

[](#resources)

- [Contributing](https://github.com/charcoalphp/.github/blob/main/CONTRIBUTING.md)
- [Report issues](https://github.com/charcoalphp/charcoal/issues) and [send pull requests](https://github.com/charcoalphp/charcoal/pulls)in the [main Charcoal repository](https://github.com/charcoalphp/charcoal)

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community25

Small or concentrated contributor base

Maturity81

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 50.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 ~57 days

Recently: every ~15 days

Total

46

Last Release

795d ago

Major Versions

0.1.10.1 → v2.1.22022-06-21

v2.2.3 → v3.1.02022-08-08

v3.1.8 → v4.0.02022-09-21

v4.1.0 → v5.0.02024-03-13

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

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

v2.1.2PHP ^7.4 || ^8.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)

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

![](https://www.gravatar.com/avatar/4229f19eecd12c2b651b6502dcc5adfba48c5770db3d2dbea55fc92c7a246b2b?d=identicon)[BeneRoch](/maintainers/BeneRoch)

---

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)")[![actions-user](https://avatars.githubusercontent.com/u/65916846?v=4)](https://github.com/actions-user "actions-user (17 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

charcoali18nintll10nread-only-repositorytranslationtranslatori18nl10ntranslationtranslatorcharcoalg11n

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

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

```
[![Health](https://phpackages.com/badges/charcoal-translator/health.svg)](https://phpackages.com/packages/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)
