Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up a locale in ZF2 from browser preferences?

In Zend framework 1 I can do

try {
    $locale = new Zend_Locale('browser'); 
} catch (Zend_Locale_Exception $e) {
    $locale = new Zend_Locale('en');   
}
$registry = Zend_Registry::getInstance();
$registry->set('Zend_Locale', $locale);

But how does it work with Zend Framework 2?

like image 396
Cawa Avatar asked Oct 02 '12 09:10

Cawa


2 Answers

I recently blogged about Zend Framework 2 and how all the i18n, l10n and locale settings work. This might be interesting for you, too, as the locale used can be set up by many ways.

Read about it: Zend Framework 2 - translate, i18n, locale

Personally i go with the following approach and then - depending on your structure - you may add locales from either database, session or cookies or whatever ;)

<?php
namespace FileManager;

use Zend\Mvc\ModuleRouteListener;

class Module
{
    public function onBootstrap($e)
    {
        $translator = $e->getApplication()->getServiceManager()->get('translator');
        $translator
          ->setLocale(\Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']))
          ->setFallbackLocale('en_US');
    }

    //...
}
like image 125
Sam Avatar answered Jan 03 '23 11:01

Sam


Judging from this RFC, the decision was taken to leave Zend_Locale out of Zend Framework 2 and rely on the core PHP I18n classes.

I would recommend reading the manual starting with the introduction to get a good understanding of the classes and then refactoring your code to use them.

like image 31
vascowhite Avatar answered Jan 03 '23 11:01

vascowhite