Application Integration
In This Article
Usage in a Slim Application
The following examples show two options for using the Translator of zend-i18n in the micro framework Slim.
More informations to Slim with a complete installation and user guide can be found under www.slimframework.com.
Setup App
$responseFactory = new Slim\Http\Factory\DecoratedResponseFactory(
new Slim\Psr7\Factory\ResponseFactory(),
new Slim\Psr7\Factory\StreamFactory()
);
$app = new Slim\App($responseFactory);
Create Translation File
Create a file for the translation messages. For example languages/de_DE.php
:
return [
'Welcome to Slim!' => 'Willkommen bei Slim!',
];
Add Translator
$container = $app->getContainer();
$container['translator'] = function ($container) {
// Create a translator instance
$translator = new Zend\I18n\Translator\Translator();
// Add translation file for German
$translator->addTranslationFile(
Zend\I18n\Translator\Loader\PhpArray::class,
__DIR__ . '/languages/de_DE.php',
'default',
'de_DE'
);
return $translator;
};
Using Translator
$app->get('/test-slim/', function ($request, $response, $args) {
// Get the translator from container
/** @var Zend\I18n\Translator\TranslatorInterface $translator */
$translator = $this->get('translator');
$response->write(
// Translate
$translator->translate('Welcome to Slim!')
);
return $response;
});
Using Slim PHP Renderer
Setup
$container['renderer'] = function($container) {
// Create a renderer instance
$renderer = new Slim\Views\PhpRenderer('./templates');
// Add the translator
$renderer->addAttribute('translator', $container->get('translator'));
return $renderer;
};
Using Translator in View Script
echo $this->translator->translate('Welcome to Slim!');
Found a mistake or want to contribute to the documentation? Edit this page on GitHub!