IPL: How to use ipl-stdlib and ipl-i18n

by | Sep 6, 2023

In my previous blogpost, I explained how easy it is to validate forms with the ipl-validator.

Today we will talk about the following two very useful libraries:

Ipl-stdlib:

All our libraries are based on this library. It provides many useful features like string handling, data class for storing data, plugins trait for loading classes, interfaces and traits that are used in other ipl libraries, and much more.

We have also introduced some new functions and methods that extend php’s built-in functions, and many more will follow.

 

Ipl-i18n:

We use this library to provide support for multiple languages in Icinga Web. This library provides a translation suite using PHP’s own gettext extension.

To use this library in your own project, you need to initialize the StaticTranslator::$instance in your bootstrap as follows:

StaticTranslator::$instance = (new GettextTranslator())
    ->addTranslationDirectory('/path/to/locales')
    ->addTranslationDirectory('/path/to/locales-of-domain', 'special') // Could also be the same directory as above
    ->setDefaultDomain('YOUR_GETTEXT_DOMAIN')
    ->setLocale('de_DE');

Now you’re ready to go. You can now translate the content of your project as following:

 

<?php 
namespace Icinga\Module\Test\Controllers;

use ipl\Web\Compat\CompatController;

class TestController extends CompatController 
{
    use Translation;

    protected $translationDomain = 'icinga';

    public function indexAction(): void
    { 
        $this->view->h = $this->translate('Hello Icinga Users'); // returns 'Hallo Icinga Benutzer'
        $this->view->d = $this->translatePlural('First blogpost', 'Not first blogpost', $this->countPosts());

       // If the default domain is set, it will be used automatically. For a different domain, you can use the following method:

        $this->view->hd = $this->translateInDomain('Foo', 'Hello Icinga Users');
        $this->view->dp = $this->translatePluralInDomain(
            'Foo',
            'First blogpost',
            'Not first blogpost',
            $this->countPosts()
        );
    }
}

 

Have a wonderful week, stay tuned.

You May Also Like…

Subscribe to our Newsletter

A monthly digest of the latest Icinga news, releases, articles and community topics.