PHP internalization with Gettext and Docker

How to configure Gettext using PHP and Docker

One thing that sets apart software applications is internalization. Developers often overlook the importance of internalization of their app. Let’s set that up.

The Docker part (likely what you are looking for)

Fortunately, there are open source tools that make translation of your app easy.

Consider using `gettext`, a GNU project for software application resources internationalization. It has been ported to many programming languages, including PHP.

To configure gettext in your Docker environment, takes only a few lines of code and 2 minutes of your time. You need to install the locales, gettext, and poedit on your operating system. We are mostly using Ubuntu and Docker, so here is what that might look like:

RUN apt-get update \
    && apt-get -y install locales \
    && apt-get -y install gettext \
    && apt-get -y install poedit \
    && apt-get clean; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*

After those are installed, you need to configure the locals that you want to support. The easiest way to configure those is to modify /etc/locale.gen file directly from your Dockerfile like so:

RUN sed -i -e 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen \
    && sed -i -e 's/# en_US ISO-8859-1/en_US ISO-8859-1/' /etc/locale.gen \
    && sed -i -e 's/# en_US.ISO-8859-15 ISO-8859-15/en_US.ISO-8859-15 ISO-8859-15/' /etc/locale.gen \
    && dpkg-reconfigure --frontend=noninteractive locales \
    && update-locale

According to documentation there is a way to use locale-gen and pass the desired locales, however this introduces other issues when building the container.

Finally, you need to install and enable the gettext php extension like so:

RUN docker-php-ext-install gettext
RUN docker-php-ext-enable gettext

Don’t forget to rebuild your Docker containers, I’m a fan of docker-compose so if you are using docker-compose simply run

docker-compose build

Further setup considerations

The above may not be all you need since we only installed one locale. However, you could apply install other locales using locale-gen. You can find all available locals by running

dpkg-reconfigure locales

Further reading

While this article only aims at providing steps to configure Gettext using Docker, actually using it in code requires the translations to be available and requires Gettext to be made aware of those translations.

Official documentation of Gettext on php.net

Official documentation of bindtextdomain on php.net. This is required in order to bind the actual translation to gettext.