Skip to content

Lab 11: Localization & Multi-language Support

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.


By completing this lab, you will:

  • Organize translations in JSON files, one per language, with dot-notation keys.
  • Wrap the Symfony Translator in a TranslationHelper class.
  • 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.

Before starting this lab, ensure you have:


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:

  1. Open a terminal in your project root
  2. Run the following command:
Terminal window
composer require symfony/translation

Objective: Store the text of your application in one JSON file per language.

Instructions:

  1. In your project root, create a lang/ folder with an en/ and an fr/ subfolder:
lang/
├── en/
│ └── messages.json
└── fr/
└── messages.json
  1. Create lang/en/messages.json with the following content:
lang/en/messages.json
{
"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"
}
}
  1. Create lang/fr/messages.json with the same keys and French values:
lang/fr/messages.json
{
"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"
}
}
  1. 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:

  1. Navigate to your app/Helpers/ directory
  2. Create a new file named TranslationHelper.php
  3. Start from the following class structure:
app/Helpers/TranslationHelper.php
<?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
}
  1. Implement the TODOs
  2. 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 key home.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.

Objective: Apply the language saved in the session on every request.

Instructions:

  1. Navigate to your app/Middleware/ directory
  2. Create a new file named LocaleMiddleware.php
  3. Start from the following class structure:
app/Middleware/LocaleMiddleware.php
<?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.
}
}
  1. Implement the TODOs
  2. Save the file

The middleware only reads the session. Changing the language is a separate POST request, which you will build in Step 7.


Objective: Register the translator and the middleware, and make translations available in every view.

  1. Open config/constants.php
  2. After the APP_VIEWS_PATH constant, add a constant named APP_LANG_PATH that combines APP_BASE_DIR_PATH with '/lang'
  3. Save the file

Step 5.2: Register the Services in the Container

Section titled “Step 5.2: Register the Services in the Container”
  1. Open config/container.php and add use statements for App\Helpers\TranslationHelper and App\Middleware\LocaleMiddleware
  2. Add the following entries to the $definitions array:
config/container.php
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)
);
},
  1. 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.

  1. Open config/middleware.php
  2. Add LocaleMiddleware before the SessionMiddleware line from Lab 4. Both must stay above ExceptionMiddleware, which is added last:
config/middleware.php
$app->addBodyParsingMiddleware();
$app->addRoutingMiddleware();
$app->add(LocaleMiddleware::class); // Added first, runs second
$app->add(SessionMiddleware::class); // Added second, runs first
$app->add(ExceptionMiddleware::class);
  1. Add use App\Middleware\LocaleMiddleware; at the top of the file
  2. Save the file

Step 5.4: Create the Global trans() Function

Section titled “Step 5.4: Create the Global trans() Function”
  1. Open config/functions.php
  2. Add the following function at the end of the file:
config/functions.php
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);
}
}
  1. 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”
  1. Open config/bootstrap.php
  2. Find the statement that builds the container:
$container = (new ContainerBuilder())
->addDefinitions($definitions)
->build();
  1. Right after it, and before the line that creates $app, add:
config/bootstrap.php
global $translator;
$translator = $container->get(\App\Helpers\TranslationHelper::class);
  1. 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:

  1. Open app/Views/common/header.php. At the very top of the file, add:
<?php global $translator; ?>
  1. In the same file, replace <html lang="en"> with:
<html lang="<?= hs($translator->getLocale()) ?>">
  1. 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>
  1. Save the file
  2. Open app/Views/homeView.php and translate the title and the text:
app/Views/homeView.php
<?php
$page_title = trans('home.title');
ViewHelper::loadHeader($page_title);
?>
<h1><?= hs(trans('home.welcome')) ?></h1>
<p><?= hs(trans('home.description')) ?></p>
  1. 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.


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.

  1. Navigate to your app/Controllers/ directory
  2. Create a new file named LocaleController.php
  3. Start from the following class structure:
app/Controllers/LocaleController.php
<?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).
}
}
  1. Implement the TODOs
  2. 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:

  • LocaleMiddleware already 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.
  1. Open app/Routes/web-routes.php and add use App\Controllers\LocaleController; at the top
  2. Outside the /admin group, add:
app/Routes/web-routes.php
// TODO: Create a POST route for '/locale' that maps to LocaleController::class 'switch' method
// Set the route name to 'locale.switch'
  1. Save the file
  1. Open app/Views/common/header.php
  2. In the navigation bar, add the following code:
app/Views/common/header.php
<?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; ?>
  1. 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.


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:

  1. Open app/Controllers/ProductsController.php
  2. In store(), update(), and delete(), replace the text of each success flash message with the matching key from the flash section of your translation files: flash.product_created, flash.product_updated, and flash.product_deleted
  3. 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.


  1. Visit http://localhost/your-app-name/. The home page should be in English, with a “Français” button in the navigation.
  2. Click “Français”. You should return to the same page, now in French, with the message “La langue a été modifiée.”
  3. Navigate to other pages. They should stay in French, because the choice is saved in the session.
  4. Refresh the page. The browser should not ask you to confirm a form resubmission.
  5. Open the developer tools, find the switcher’s hidden locale field, change its value to es, and click the button. You should see “Cette langue n’est pas disponible.” and the language should not change.
  6. Inspect the <html> tag. Its lang attribute should be fr while the page is in French.
  7. Create a product in the admin panel. The success message should be in the current language.
  8. Add a key only to lang/en/messages.json and display it with trans() 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.

Before submitting your lab, verify the following:

  • lang/en/messages.json and lang/fr/messages.json exist and have the same keys
  • TranslationHelper.php and LocaleController.php exist and are implemented
  • LocaleMiddleware is added before SessionMiddleware in config/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