Skip to content

Instantly share code, notes, and snippets.

@juriansluiman
Created July 11, 2012 13:14
Show Gist options
  • Save juriansluiman/3090332 to your computer and use it in GitHub Desktop.
Save juriansluiman/3090332 to your computer and use it in GitHub Desktop.
Set a default locale for your application in Zend Framework 2
<?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);
}
}
}
@Saeven
Copy link

Saeven commented Apr 24, 2015

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() )) )

Copy link

ghost commented Apr 27, 2017

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