Zend Framework 2 (ZF2) dynamic locale

1.5k views Asked by At

I am looking for a way to add translations to my ZF2 application, using globals in my URL. Is there anyway to do this for the whole application at once?

A typpical URL would look like this: http://domain.com/en_GB/user/index

The first part (en_GB) should be used to show the correct translation.

Besides that, it would be nice, if it is possible to set this router part optional. So, if I should go to http://domain.com/user/index (without the locale part) to my application, it should automatically take the browser locale.

I hope I am clear enough, if any additions are needed to this question, feel free to ask.

Thanx in advance

2

There are 2 answers

0
DrBeza On

I would suggest extending the Segment route class and adding in the optional locale constraint and segment part if missing. Call the optional variable something application wide such as 'locale'.

Then create a 'route' event in the main module bootstrap, this event will fire once a route has been matched. The callback function that is fired will have access to the RouteMatch object through the passed event, letting you gain access to the 'locale' value. Then you can do some checks and set the application locale.

0
Arthur On

@DrBeza,

Thank you for your answer. I don't know if this is the correct way, but I created the next solution:

in /config/global.php I added this part

'translator' => array(
        'locale' => 'nl_NL',        
        'translation_file_patterns' => array(
            array(
                'type'     => 'phpArray',
                'base_dir' => __DIR__ . '/../../language',
                'pattern'  => '%s.php',
            ),
        ),
    ),

in /module/[modulename]/config/module.config.php I added this part to set the first part of the URL containing the locale

'router' => array(
        'routes' => array(
            'user' => array(
                'options' => array(
                    'route'    => '[/:lang]/user[/:action][/:id]',
                    'constraints' => array(
                        'lang'  => '([a-z]{2})+(_)+([A-Z]{2})',
                    ),
                ),
            ),
        ),
    ),

in /config/local.php I added this code to fetch the locale from the URL:

http://domain.com/[locale][module][controller]

$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segment = explode('/', $_SERVER['REQUEST_URI_PATH']);

And I added this part to load the locale dynamicly:

return array(
   'translator' => array(
   'locale' => $segment[1],
);