Lab 11: Localization & Multi-language Support
Additional Resources
Section titled “Additional Resources”- Localization & Multi-language Support
- Middleware in Slim 4
- Lab 4: Session Middleware and Flash Messages
- Symfony Translation Documentation ↗
Overview
Section titled “Overview”In this lab, you will make your e-commerce application available in English and French. You will store the text of your pages in translation files, build a TranslationHelper around the Symfony Translation component, and add a language switcher to the public header. The chosen language is saved in the session, and a LocaleMiddleware applies it on every request.
Learning Objectives
Section titled “Learning Objectives”By completing this lab, you will:
- Organize translations in JSON files, one per language, with dot-notation keys.
- Wrap the Symfony Translator in a
TranslationHelperclass. - Apply the user’s language on every request with a
LocaleMiddleware, and register it in the right order. - Build a language switcher that changes the language with a POST request and redirects back.
- Replace hardcoded text in views and flash messages with translation keys.
Prerequisites
Section titled “Prerequisites”Before starting this lab, ensure you have:
- Completed Lab 4: Session Middleware and Flash Messages. This lab saves the chosen language with
SessionManagerand displays feedback withFlashMessage. - Completed Lab 5 and Lab 6. Step 8 translates the flash messages of your
ProductsController. - Read Localization & Multi-language Support.
Step 1: Install the Symfony Translation Component
Section titled “Step 1: Install the Symfony Translation Component”Objective: Add the translation library to your project.
Instructions:
- Open a terminal in your project root
- Run the following command:
composer require symfony/translationStep 2: Create the Translation Files
Section titled “Step 2: Create the Translation Files”Objective: Store the text of your application in one JSON file per language.
Instructions:
- In your project root, create a
lang/folder with anen/and anfr/subfolder:
lang/├── en/│ └── messages.json└── fr/ └── messages.json- Create
lang/en/messages.jsonwith the following content:
{ "nav": { "home": "Home", "products": "Products", "cart": "Cart" }, "home": { "title": "Home", "welcome": "Welcome to our e-commerce store", "description": "Browse our products and enjoy shopping with us." }, "locale": { "en": "English", "fr": "Français", "changed": "The language has been changed.", "invalid": "This language is not available." }, "flash": { "product_created": "The product has been created.", "product_updated": "The product has been updated.", "product_deleted": "The product has been deleted." }, "common": { "save": "Save", "cancel": "Cancel", "delete": "Delete" }}- Create
lang/fr/messages.jsonwith the same keys and French values:
{ "nav": { "home": "Accueil", "products": "Produits", "cart": "Panier" }, "home": { "title": "Accueil", "welcome": "Bienvenue dans notre boutique en ligne", "description": "Parcourez nos produits et profitez de vos achats." }, "locale": { "en": "English", "fr": "Français", "changed": "La langue a été modifiée.", "invalid": "Cette langue n'est pas disponible." }, "flash": { "product_created": "Le produit a été créé.", "product_updated": "Le produit a été mis à jour.", "product_deleted": "Le produit a été supprimé." }, "common": { "save": "Enregistrer", "cancel": "Annuler", "delete": "Supprimer" }}- Save both files with UTF-8 encoding, so the French accents (é, è, à, ç) display correctly
Both files must have the same keys; only the values differ. The language names under locale are written in their own language in both files, so a French speaker can find “Français” even while the page is in English.
As you translate more pages, add keys to both files. Use descriptive keys (products.add_to_cart, not products.btn1). Translations can also contain placeholders for dynamic values:
{ "user": { "greeting": "Hello, %name%!" }}trans('user.greeting', ['%name%' => 'Alice'])You can check your JSON syntax with JSONLint ↗.
Step 3: Create the TranslationHelper Class
Section titled “Step 3: Create the TranslationHelper Class”Objective: Wrap the Symfony Translator in a class that loads your files and manages the current language.
The following Translator methods are the ones you will need:
$translator = new Translator(string $locale);$translator->setFallbackLocales(array $locales): void;$translator->addLoader(string $format, LoaderInterface $loader): void;$translator->addResource(string $format, string $resource, string $locale, string $domain): void;$translator->trans(string $id, array $parameters, string $domain, string $locale): string;$translator->setLocale(string $locale): void;Instructions:
- Navigate to your
app/Helpers/directory - Create a new file named
TranslationHelper.php - Start from the following class structure:
<?php
declare(strict_types=1);
namespace App\Helpers;
use Symfony\Component\Translation\Translator;use Symfony\Component\Translation\Loader\JsonFileLoader;
class TranslationHelper{ private Translator $translator; private string $currentLocale; private string $defaultLocale; private string $langPath; private array $availableLocales;
/** * @param string $langPath Path to language files directory * @param string $defaultLocale Default locale (fallback) * @param array $availableLocales List of available locales */ public function __construct( string $langPath, string $defaultLocale = 'en', array $availableLocales = ['en', 'fr'] ) { // TODO: Initialize class properties, create a Translator instance, // configure the fallback locale, register the JSON file loader, // and load all translation files. }
/** * Load translation files for all available locales. */ private function loadTranslations(): void { // TODO: Loop through available locales, build the file path to each // locale's messages.json, and register each existing file // with the translator. }
/** * Translate a message. * * @param string $key Translation key (supports dot notation: 'home.welcome') * @param array $parameters Parameters to replace in translation * @param string|null $locale Override current locale for this translation * @return string Translated message */ public function trans(string $key, array $parameters = [], ?string $locale = null): string { // TODO: Translate the given key using the current locale // (or the override locale if provided). }
/** * Set the current locale. * * @param string $locale Locale code (e.g., 'en', 'fr') * @throws \InvalidArgumentException If locale is not available */ public function setLocale(string $locale): void { // TODO: Validate that the locale is available, then update both // the class property and the translator. }
// TODO: Implement the following getter methods that return // the corresponding class properties: // - getLocale(): string // - getDefaultLocale(): string // - getAvailableLocales(): array // - isLocaleAvailable(string $locale): bool}- Implement the TODOs
- Save the file
Hints:
- The format name for the JSON loader is
'json', and the translation domain is'messages'(the file name). - The JSON loader turns nested keys into dot notation, so
{"home": {"welcome": "..."}}becomes the keyhome.welcome. - With the fallback locale set to
en, a key missing from the French file is looked up in the English file. If it is missing there too,trans()returns the key itself.
Step 4: Create the LocaleMiddleware
Section titled “Step 4: Create the LocaleMiddleware”Objective: Apply the language saved in the session on every request.
Instructions:
- Navigate to your
app/Middleware/directory - Create a new file named
LocaleMiddleware.php - Start from the following class structure:
<?php
declare(strict_types=1);
namespace App\Middleware;
use App\Helpers\SessionManager;use App\Helpers\TranslationHelper;use Psr\Http\Message\ResponseInterface;use Psr\Http\Message\ServerRequestInterface as Request;use Psr\Http\Server\MiddlewareInterface;use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
class LocaleMiddleware implements MiddlewareInterface{ public function __construct(private TranslationHelper $translator) { }
public function process(Request $request, RequestHandler $handler): ResponseInterface { // TODO: 1. Read the locale saved in the session under the key 'locale'.
// TODO: 2. If a locale is saved and it is available, set it on the translator. // Otherwise, keep the default locale.
// TODO: 3. Pass the request to the next handler. }}- Implement the TODOs
- Save the file
The middleware only reads the session. Changing the language is a separate POST request, which you will build in Step 7.
Step 5: Configure the Application
Section titled “Step 5: Configure the Application”Objective: Register the translator and the middleware, and make translations available in every view.
Step 5.1: Add the Language Path Constant
Section titled “Step 5.1: Add the Language Path Constant”- Open
config/constants.php - After the
APP_VIEWS_PATHconstant, add a constant namedAPP_LANG_PATHthat combinesAPP_BASE_DIR_PATHwith'/lang' - Save the file
Step 5.2: Register the Services in the Container
Section titled “Step 5.2: Register the Services in the Container”- Open
config/container.phpand addusestatements forApp\Helpers\TranslationHelperandApp\Middleware\LocaleMiddleware - Add the following entries to the
$definitionsarray:
TranslationHelper::class => function (ContainerInterface $container): TranslationHelper { return new TranslationHelper( APP_LANG_PATH, 'en', ['en', 'fr'] );},
LocaleMiddleware::class => function (ContainerInterface $container): LocaleMiddleware { return new LocaleMiddleware( $container->get(TranslationHelper::class) );},- Save the file
The container creates one TranslationHelper and shares it. The middleware, your controllers, and the trans() function all use the same instance, so the locale set by the middleware applies everywhere.
Step 5.3: Register the Middleware
Section titled “Step 5.3: Register the Middleware”- Open
config/middleware.php - Add
LocaleMiddlewarebefore theSessionMiddlewareline from Lab 4. Both must stay aboveExceptionMiddleware, which is added last:
$app->addBodyParsingMiddleware();$app->addRoutingMiddleware();
$app->add(LocaleMiddleware::class); // Added first, runs second$app->add(SessionMiddleware::class); // Added second, runs first
$app->add(ExceptionMiddleware::class);- Add
use App\Middleware\LocaleMiddleware;at the top of the file - Save the file
Step 5.4: Create the Global trans() Function
Section titled “Step 5.4: Create the Global trans() Function”- Open
config/functions.php - Add the following function at the end of the file:
if (!function_exists('trans')) { /** * Translate a message using the application's translation helper. * * @param string $key Translation key (supports dot notation: 'home.welcome') * @param array $parameters Parameters to replace in translation * @param string|null $locale Override current locale for this translation * @return string Translated message or the key itself if translation not found */ function trans(string $key, array $parameters = [], ?string $locale = null): string { global $translator;
if (!isset($translator)) { return $key; }
return $translator->trans($key, $parameters, $locale); }}- Save the file
With this function, views and controllers can write trans('home.welcome') instead of fetching the translator from the container.
Step 5.5: Initialize the Global Translator
Section titled “Step 5.5: Initialize the Global Translator”- Open
config/bootstrap.php - Find the statement that builds the container:
$container = (new ContainerBuilder()) ->addDefinitions($definitions) ->build();- Right after it, and before the line that creates
$app, add:
global $translator;$translator = $container->get(\App\Helpers\TranslationHelper::class);- Save the file
Step 6: Translate the Public Layout and Home Page
Section titled “Step 6: Translate the Public Layout and Home Page”Objective: Replace hardcoded text with translation keys, and declare the page’s language.
Instructions:
- Open
app/Views/common/header.php. At the very top of the file, add:
<?php global $translator; ?>- In the same file, replace
<html lang="en">with:
<html lang="<?= hs($translator->getLocale()) ?>">- Replace the text of your navigation links with translation keys. Build each URL with
APP_BASE_URL, as in the other labs:
<a href="<?= APP_BASE_URL ?>/"><?= hs(trans('nav.home')) ?></a><a href="<?= APP_BASE_URL ?>/products"><?= hs(trans('nav.products')) ?></a><a href="<?= APP_BASE_URL ?>/cart"><?= hs(trans('nav.cart')) ?></a>- Save the file
- Open
app/Views/homeView.phpand translate the title and the text:
<?php$page_title = trans('home.title');ViewHelper::loadHeader($page_title);?>
<h1><?= hs(trans('home.welcome')) ?></h1><p><?= hs(trans('home.description')) ?></p>- Save the file
Always wrap trans() output in hs(). Translation files are text that someone edits, and the value is printed into HTML like any other string.
The lang attribute tells browsers, screen readers, and search engines which language the page is in. Without it, a screen reader would read French text with English pronunciation.
Step 7: Build the Language Switcher
Section titled “Step 7: Build the Language Switcher”Objective: Let users change the language with a POST request that saves the choice and returns them to the same page.
Changing the language changes state (the value saved in the session), so it is a POST request, like every other request that changes state.
Step 7.1: Create the LocaleController
Section titled “Step 7.1: Create the LocaleController”- Navigate to your
app/Controllers/directory - Create a new file named
LocaleController.php - Start from the following class structure:
<?php
namespace App\Controllers;
use App\Helpers\FlashMessage;use App\Helpers\SessionManager;use App\Helpers\TranslationHelper;use DI\Container;use Psr\Http\Message\ResponseInterface as Response;use Psr\Http\Message\ServerRequestInterface as Request;
class LocaleController extends BaseController{ public function __construct(Container $container, private TranslationHelper $translator) { parent::__construct($container); }
/** * Change the language (POST /locale). */ public function switch(Request $request, Response $response, array $args): Response { // TODO: 1. Read the 'locale' field from the submitted form.
// TODO: 2. If the locale is not available, set the error flash message // trans('locale.invalid') using the FlashMessage helper class.
// TODO: 3. Otherwise: // - save the locale in the session under the key 'locale' // - switch the translator to the new locale as well, so the // success message below is already in the new language // - set the success flash message trans('locale.changed') // using the FlashMessage helper class
// TODO: 4. Redirect back to the page the user came from (see the hint below). }}- Implement the TODOs
- Save the file
Redirecting back: the browser sends the address of the page that contained the form in the Referer header. Only redirect to it if it starts with your application’s address (APP_BASE_URL, for example http://localhost/your-app-name); otherwise, a forged header could send the user to another site. If the header is missing or points elsewhere, fall back to the home page:
$referer = $request->getHeaderLine('Referer');
if (str_starts_with($referer, APP_BASE_URL . '/')) { return $response->withStatus(302)->withHeader('Location', $referer);}
return $this->redirect($request, $response, 'home.index');Hints:
LocaleMiddlewarealready ran before this method, with the old locale. That is why TODO 3 also switches the translator: otherwise the “language changed” message would appear in the previous language.
Step 7.2: Register the Route
Section titled “Step 7.2: Register the Route”- Open
app/Routes/web-routes.phpand adduse App\Controllers\LocaleController;at the top - Outside the
/admingroup, add:
// TODO: Create a POST route for '/locale' that maps to LocaleController::class 'switch' method// Set the route name to 'locale.switch'- Save the file
Step 7.3: Add the Switcher to the Header
Section titled “Step 7.3: Add the Switcher to the Header”- Open
app/Views/common/header.php - In the navigation bar, add the following code:
<?php foreach ($translator->getAvailableLocales() as $locale): ?> <?php if ($locale !== $translator->getLocale()): ?> <form method="POST" action="<?= APP_BASE_URL ?>/locale" class="d-inline"> <input type="hidden" name="locale" value="<?= hs($locale) ?>"> <button type="submit" class="btn btn-link nav-link"> <?= hs(trans('locale.' . $locale)) ?> </button> </form> <?php endif; ?><?php endforeach; ?>- Save the file
The switcher shows one button for every language except the current one. The button labels come from the locale keys, so adding a language only requires a new translation file and a new locale key, not a change to this code.
Step 8: Translate Flash Messages
Section titled “Step 8: Translate Flash Messages”Objective: Make the messages set in controllers follow the user’s language too.
Views are not the only place with hardcoded text: flash messages are written in controllers.
Instructions:
- Open
app/Controllers/ProductsController.php - In
store(),update(), anddelete(), replace the text of each success flash message with the matching key from theflashsection of your translation files:flash.product_created,flash.product_updated, andflash.product_deleted - Save the file
Apply the same change to the flash messages of your other controllers, adding keys to both translation files as you go. trans() returns a plain string, so you pass its result to FlashMessage::success() like any other message.
Step 9: Test Your Localization
Section titled “Step 9: Test Your Localization”- Visit
http://localhost/your-app-name/. The home page should be in English, with a “Français” button in the navigation. - Click “Français”. You should return to the same page, now in French, with the message “La langue a été modifiée.”
- Navigate to other pages. They should stay in French, because the choice is saved in the session.
- Refresh the page. The browser should not ask you to confirm a form resubmission.
- Open the developer tools, find the switcher’s hidden
localefield, change its value toes, and click the button. You should see “Cette langue n’est pas disponible.” and the language should not change. - Inspect the
<html>tag. Itslangattribute should befrwhile the page is in French. - Create a product in the admin panel. The success message should be in the current language.
- Add a key only to
lang/en/messages.jsonand display it withtrans()while the page is in French. The English text should appear (fallback). Then display a key that exists in neither file: the key itself should appear.
Verification Checklist
Section titled “Verification Checklist”Before submitting your lab, verify the following:
-
lang/en/messages.jsonandlang/fr/messages.jsonexist and have the same keys -
TranslationHelper.phpandLocaleController.phpexist and are implemented -
LocaleMiddlewareis added beforeSessionMiddlewareinconfig/middleware.php - The switcher is a POST form, and changing the language returns to the same page
- The language stays the same while navigating between pages
- An unavailable locale shows an error and leaves the language unchanged
- The
<html lang>attribute matches the current language - Product flash messages are translated