PHPackages                             m1sh0u/polyglot-php - 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. m1sh0u/polyglot-php

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

m1sh0u/polyglot-php
===================

Polyglot.php is a replica of the Airbnb's Polyglot.js I18n helper library

v1.3(3y ago)110.2k↓40.9%1MITPHPPHP &gt;=7.2

Since May 27Pushed 3y ago1 watchersCompare

[ Source](https://github.com/M1Sh0u/polyglot.php)[ Packagist](https://packagist.org/packages/m1sh0u/polyglot-php)[ Docs](https://github.com/m1sh0u/polyglot.php)[ RSS](/packages/m1sh0u-polyglot-php/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (1)Versions (5)Used By (1)

Polyglot.php
============

[](#polyglotphp)

[![Latest Version on Packagist](https://camo.githubusercontent.com/121fafd1b0f5ebcc88dc6431b85b102cee4cece7cdf5b18a4e800758d020206e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d31736830752f706f6c79676c6f742d7068702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/m1sh0u/polyglot-php)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Tests](https://github.com/M1Sh0u/polyglot.php/workflows/run-tests/badge.svg?branch=master)](https://github.com/M1Sh0u/polyglot.php/workflows/run-tests/badge.svg?branch=master)[![Code Quality](https://camo.githubusercontent.com/066a64897019dba4738caa806d18b3167d4c2c5bb45fe37fe14897e476c6e709/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f4d31536830752f706f6c79676c6f742e7068702f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572267374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/M1Sh0u/polyglot.php/?branch=master)[![Total Downloads](https://camo.githubusercontent.com/fd2238d430d40b1aa5ebee920f8581ce54644e49137ac34f22ad101d17356c29/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d31736830752f706f6c79676c6f742d7068702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/m1sh0u/polyglot-php)

Polyglot.php is a tiny I18n helper library written in PHP, which is based entirely on the Polyglot.js Airbnb's I18n javascript library.

The reason behind the decision to replicate the Airbnb's javascript library was to have a small, but yet powerful library, for developers to use the same way of internationalizing their PHP back-ends as they do in the front-end apps.

Polylglot doesn’t perform any translation; it simply gives you a way to manage translated phrases from your server-side PHP application.

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

[](#installation)

install with [composer](https://getcomposer.org):

```
$ composer require m1sh0u/polyglot-php

```

### Running the tests

[](#running-the-tests)

Clone the repo, run `composer update --prefer-dist --dev`, and `composer test`, or `composer test-win` for windows.

Usage
-----

[](#usage)

### Instantiation

[](#instantiation)

First, create an instance of the `Polyglot` class, which you will use for translation.

```
$polyglot = new Polyglot();
```

Polyglot is class-based so you can maintain different sets of phrases at the same time, possibly in different locales.

See [Options Overview](#options-overview) for information about the options array you can choose to pass to `new Polyglot`.

### Translation

[](#translation)

Tell Polyglot what to say by simply giving it a phrases key-value pair, where the key is the canonical name of the phrase and the value is the already-translated string.

```
$polyglot->extend([
  "hello" => "Hello"
]);

$polyglot->t("hello");
=> "Hello"
```

You can also pass a mapping at instantiation, using the key `phrases`:

```
$polyglot = new Polyglot(['phrases' => ["hello" => "Hello"]]);
```

Polyglot doesn’t do the translation for you. It’s up to you to give it the proper phrases for the user’s locale.

### Interpolation

[](#interpolation)

`Polyglot->t()` also provides interpolation. Pass an array with key-value pairs of interpolation arguments as the second parameter.

```
$polyglot->extend([
  "hello_name" => "Hola, %{name}."
]);

$polyglot->t("hello_name", ["name" => "DeNiro"]);
=> "Hola, DeNiro."
```

Polyglot also supports nested phrase objects.

```
$polyglot->extend([
  "nav" => [
    "hello" => "Hello",
    "hello_name" => "Hello, %{name}",
    "sidebar" => [
      "welcome" => "Welcome"
    ]
  ]
]);

$polyglot->t("nav.sidebar.welcome");
=> "Welcome"
```

The substitution variable syntax is customizable.

```
$polyglot = new Polyglot({
  "phrases" => [
    "hello_name" => "Hola {{name}}"
  ],
  "interpolation" => ["prefix" => "{{", "suffix" => "}}"]
});

$polyglot->t("hello_name", ["name" => "DeNiro"]);
=> "Hola, DeNiro."
```

### Pluralization

[](#pluralization)

For pluralization to work properly, you need to tell Polyglot what the current locale is. You can use `$polyglot->locale("fr")` to set the locale to, for example, French. This method is also a getter:

```
$polyglot->locale()
=> "fr"
```

You can also pass this in during instantiation.

```
$polyglot = new Polyglot(["locale" => "fr"]);
```

Currently, the *only* thing that Polyglot uses this locale setting for is pluralization.

Polyglot provides a very basic pattern for providing pluralization based on a single string that contains all plural forms for a given phrase. Because various languages have different nominal forms for zero, one, and multiple, and because the noun can be before or after the count, we have to be overly explicit about the possible phrases.

To get a pluralized phrase, still use `$polyglot->t()` but use a specially-formatted phrase string that separates the plural forms by the delimiter `||||`, or four vertical pipe characters.

For pluralizing "car" in English, Polyglot assumes you have a phrase of the form:

```
$polyglot->extend([
  "num_cars" => "%{smart_count} car |||| %{smart_count} cars",
]);
```

In English (and German, Spanish, Italian, and a few others) there are only two plural forms: singular and not-singular.

Some languages get a bit more complicated. In Czech, there are three separate forms: 1, 2 through 4, and 5 and up. Russian is even more involved.

```
$polyglot = new Polyglot(["locale" => "cs"]); // Czech
$polyglot->extend([
  "num_foxes" => "Mám %{smart_count} lišku |||| Mám %{smart_count} lišky |||| Mám %{smart_count} lišek"
])
```

`$polyglot->t()` will choose the appropriate phrase based on the provided `smart_count` option, whose value is a number.

```
$polyglot->t("num_cars", ["smart_count" => 0]);
=> "0 cars"

$polyglot->t("num_cars", ["smart_count" => 1]);
=> "1 car"

$polyglot->t("num_cars", ["smart_count" => 2]);
=> "2 cars"
```

As a shortcut, you can also pass a number to the second parameter:

```
$polyglot->t("num_cars", 2);
=> "2 cars"
```

### Custom plural rules

[](#custom-plural-rules)

If needed, one can replace the existing plural rules or specify new custom plural rules for certain locales. The custom plural rules must be objects which implements `Polyglot\Pluralization\Rules\RuleInterface`. They will be passed to the Polyglot `pluralRules` option as a key-value pair where the key is the locale and the value is the custom rule object.

Let's define a custom plural rule for romanian language:

```
use Polyglot\Pluralization\Rules\RuleInterface;

class RomanianRule implements RuleInterface
{
    public function decide(int $n): int
    {
        return $n !== 1 ? 1 : 0;
    }
}
```

Now you can pass it to the Polyglot options to be used whenever the `ro` locale is used for pluralization:

```
$polyglot = new Polyglot([
    'phrases' => ['num_cars' => '%{smart_count} mașină |||| %{smart_count} mașini'],
    'locale' => 'ro',
    'pluralRules' => ['ro' => new RomanianRule()]
]);

$polyglot->t('num_cars', 1)
=> 1 mașină
$polyglot->t('num_cars', 6)
=> 6 mașini
```

Public Instance Methods
-----------------------

[](#public-instance-methods)

### Polyglot-&gt;t($key, $interpolationOptions)

[](#polyglot-tkey-interpolationoptions)

The most-used method. Provide a key, and `t()` will return the phrase.

```
$polyglot->t("hello");
=> "Hello"
```

The phrase value is provided first by a call to `$polyglot->extend()` or `$polyglot->replace()`.

Pass in an object as the second argument to perform interpolation.

```
$polyglot->t("hello_name", ["name" => "Spike"]);
=> "Hello, Spike"
```

Pass a number as the second argument as a shortcut to `smart_count`:

```
// same as: $polyglot->t("car", ["smart_count" => 2]);
$polyglot->t("car", 2);
=> "2 cars"
```

If you like, you can provide a default value in case the phrase is missing. Use the special option key "\_" to specify a default.

```
$polyglot->t("i_like_to_write_in_language", [
  "_" => "I like to write in %{language}.",
  "language" => "JavaScript"
]);
=> "I like to write in JavaScript."
```

### Polyglot-&gt;extend($phrases)

[](#polyglot-extendphrases)

Use `extend` to tell Polyglot how to translate a given key.

```
$polyglot->extend([
  "hello" => "Hello",
  "hello_name" => "Hello, %{name}"
]);
```

The key can be any string. Feel free to call `extend` multiple times; it will override any phrases with the same key, but leave existing phrases untouched.

### Polyglot-&gt;unset($keyOrArray)

[](#polyglot-unsetkeyorarray)

Use `unset` to selectively remove keys from a polyglot instance. `unset` accepts one argument: either a single string key, or an array whose keys are string keys, and whose values are ignored unless they are nested arrays (in the same format).

Example:

```
$polyglot->unset('some_key');
$polyglot->unset([
  'hello' => 'Hello',
  'hello_name' => 'Hello, %{name}',
  'foo' => [
    'bar' => 'This phrase’s key is "foo.bar"'
  ]
]);
```

### Polyglot-&gt;locale(?$localeToSet)

[](#polyglot-localelocaletoset)

Get or set the locale (also can be set using the [constructor option](#options-overview), which is used only for pluralization. If a truthy value is provided, it will set the locale. Afterwards, it will return it.

### Polyglot-&gt;clear()

[](#polyglot-clear)

Clears all phrases. Useful for special cases, such as freeing up memory if you have lots of phrases but no longer need to perform any translation. Also used internally by `replace`.

### Polyglot-&gt;replace($phrases)

[](#polyglot-replacephrases)

Completely replace the existing phrases with a new set of phrases. Normally, just use `extend` to add more phrases, but under certain circumstances, you may want to make sure no old phrases are lying around.

### Polyglot-&gt;has($key)

[](#polyglot-haskey)

Returns `true` if the key does exist in the provided phrases, otherwise it will return `false`.

### Polyglot-&gt;phrases()

[](#polyglot-phrases)

Returns all the phrases.

### Polyglot-&gt;transformPhrase($phrase\[, $substitutions\[, $locale\[, $tokenRegex\]\]\])

[](#polyglot-transformphrasephrase-substitutions-locale-tokenregex)

- Takes a phrase string and transforms it by choosing the correct plural form and interpolating it. This method is used internally by `t`.
- The correct plural form is selected if `$substitutions['smart_count']` is set.
- You can pass in a number instead of an array as `$substitutions` as a shortcut for `smart_count`.
- You should pass in a third argument, the locale, to specify the correct plural type. It defaults to `'en'` which has 2 plural forms.
- You should pass in a forth argument, to specify the interpolation token regex. It defaults to `~%{(.*?)}~`. Note: the regex delimiter `~` is included by default.

Options Overview
----------------

[](#options-overview)

`new Polyglot` accepts a number of options:

- `phrases`: a key/value map of translated phrases.
- `locale`: a string describing the locale (language and region) of the translation, to apply pluralization rules. see [Pluralization](#pluralization)
- `delimiter`: the delimiter used for pluralization. The default delimiter is `||||`. see [Pluralization](#pluralization)
- `allowMissing`: a boolean to control whether missing keys in a `t` call are allowed. If `false`, by default, a missing key is returned and a warning is issued.
- `onMissingKey`: if `allowMissing` is `true`, and this option is a function, then it will be called instead of the default functionality. Arguments passed to it are `$key`, `$options`, `$locale`, `$tokenRegex` and `Polyglot $polyglot`. The return of this function will be used as a translation fallback when `$polyglot->t('missing.key')` is called (hint: return the key).
- `interpolation`: an array to change the substitution syntax for interpolation by setting the `prefix` and `suffix` fields.
- `pluralRules`: replace or add new plural rules for certain locales by providing a key-value pair where the key is the locale and the value is the plural rule object implementing `Polyglot\Pluralization\Rules\RuleInterface`

Related projects
----------------

[](#related-projects)

- [Polyglot.js](https://airbnb.io/polyglot.js/): Polyglot.js is a tiny I18n helper library written in JavaScript, made to work both in the browser and in CommonJS environments (Node). It provides a simple solution for interpolation and pluralization, based off of Airbnb’s experience adding I18n functionality to its Backbone.js and Node apps.

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity25

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~263 days

Total

4

Last Release

1392d ago

PHP version history (3 changes)v1.0PHP ^7.1

v1.1PHP ^7.2

v1.3PHP &gt;=7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/3e193a0831f8a49b4fa04eba02a6fd28224a5347fbf2603668c9f30eed1f85f4?d=identicon)[M1Sh0u](/maintainers/M1Sh0u)

---

Top Contributors

[![M1Sh0u](https://avatars.githubusercontent.com/u/3706005?v=4)](https://github.com/M1Sh0u "M1Sh0u (8 commits)")

---

Tags

i18nlanguagetranslatepolyglot

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/m1sh0u-polyglot-php/health.svg)

```
[![Health](https://phpackages.com/badges/m1sh0u-polyglot-php/health.svg)](https://phpackages.com/packages/m1sh0u-polyglot-php)
```

###  Alternatives

[gettext/languages

gettext languages with plural rules

7530.3M11](/packages/gettext-languages)[aplus/language

Aplus Framework Language Library

2351.7M15](/packages/aplus-language)[punic/punic

PHP-Unicode CLDR

1542.9M29](/packages/punic-punic)[lajax/yii2-translate-manager

Translation management extension for Yii 2

227578.8k13](/packages/lajax-yii2-translate-manager)[optimistdigital/nova-translatable

A laravel-translatable extension for Laravel Nova.

202427.4k5](/packages/optimistdigital-nova-translatable)[outl1ne/nova-translatable

A laravel-translatable extension for Laravel Nova.

203416.9k8](/packages/outl1ne-nova-translatable)

PHPackages © 2026

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