Created
July 11, 2012 13:14
-
-
Save juriansluiman/3090332 to your computer and use it in GitHub Desktop.
Set a default locale for your application in Zend Framework 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Application; | |
use Locale; | |
use Zend\EventManager\Event; | |
use Zend\ModuleManager\Feature; | |
class Module implements | |
Feature\BootstrapListenerInterface | |
{ | |
public function onBootstrap(Event $e) | |
{ | |
$default = 'nl'; | |
$supported = array('en', 'en-GB'); | |
$app = $e->getApplication(); | |
$headers = $app->getRequest()->getHeaders(); | |
if ($headers->has('Accept-Language')) { | |
$locales = $headers->get('Accept-Language')->getPrioritized(); | |
// Loop through all locales, highest priority first | |
foreach ($locales as $locale) { | |
if (!!($match = Locale::lookup($supported, $locale))) { | |
// The locale is one of our supported list | |
Locale::setDefault($match); | |
break; | |
} | |
} | |
if (!$match) { | |
// Nothing from the supported list is a match | |
Locale::setDefault($default); | |
} | |
} else { | |
Locale::setDefault($default); | |
} | |
} | |
} |
Stumbled onto this, thanks. Had to make a slight revision to make it work.
$locales = $headers->get('Accept-Language')->getPrioritized();
/** @var LanguageFieldValuePart $locale */
foreach ($locales as $locale){
if( !!($match = Locale::lookup($other_locales, $locale->getTypeString() )) )
Thanks very much vor this snippet, which has worked for us very well until now. Unfortunately, recently we discovered a bug.
Think of the following:
$default = 'de_DE';
$supported = array('de_DE', 'en-GB');
The system also includes language files for exactly those locales.
Now, along comes a visitor:
Accept-Language: de,en-US;q=0.7,en;q=0.3`
Theory: He would get to see a German application.
Fact: He gets the English version.
We need to extend the snippet to also include sublocales or related locales (de_AT etc.) in its search. Currently working on that.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Apologize, I was not aware of that bit of information!
Regards