slick/i18n

Internationalization and string translation package Slick Framework

v1.3.1 2017-11-19 23:53 UTC

This package is auto-updated.

Last update: 2024-10-20 11:55:07 UTC


README

Latest Version on Packagist Software License Build Status Quality Score Total Downloads

Slick I18n is a simple translation and internationalization package. It depends on Zend/I18n which is a complete translation suite that supports all major formats and includes popular features like plural translations and text domains.

This package is compliant with PSR-2 code standards and PSR-4 autoload standards. It also applies the semantic version 2.0.0 specification.

Install

Via Composer

$ composer require slick/i18n

Usage

Messages file

Create a messages file:

/**
 * pt_PT messages file
 */

return [
    '' => array(
            'plural_forms' => 'nplurals=2; plural=n!=1;'
        ),
    'Hello world' => 'Olá mundo',
    'User' => ['Utilizador', 'Utilizadores'],
    'Users' => ''
];

save this file in ./i18n/pt_PT/messages.php.

Language negotiation and setup

Now lets get our translator:

use Slick\I18n\Language;
use Slick\I18n\Translation;
use Slick\I18n\Translator;

/**
 * Set locale based on the browser accept language
 */
$locale = 'en_US';
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
    $locale = \Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
}

$translation = new Translation(new Language($locale), __DIR__.'/i18n');
$translator = new Translator($translation);

    
setlocale(LC_ALL, $locale);

The code above is using the browser's language to set the locale for our translator object. From now on just use the translation methods on the strings you want to translate.

Message translation

echo $translator->translate('Hello world');  // will output 'Olá mundo' 

Plural translation

echo $translator->translatePlural('User', 'Users', 2);  // will output 'Utilizadores' 

Using in your classes

You can add translation functionality to your classes by using the TranslateMethods trait and injecting the translator.

use Slick\I18n\TranslateMethods;
use Slick\I18n\TranslationCapableInterface;
use Slick\I18n\TranslatotInterface;

class MyClass implements TranslationCapableInterface
{

    use TranslateMethods;

    public function __construct(TranslatotInterface $translator)
    {
        $this->tranlator = $translator;
    }  
    
    public function getUsers()
    {
        return $this->translatePlural('User', 'Users', $this->getUserCount());
    }
}
 

Change log

Please see CHANGELOG for more information on what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email slick.framework@gmail.com instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.