Skip to content

Instantly share code, notes, and snippets.

@DASPRiD
Created April 17, 2012 09:22
Show Gist options
  • Save DASPRiD/2404837 to your computer and use it in GitHub Desktop.
Save DASPRiD/2404837 to your computer and use it in GitHub Desktop.
Locale or language in URL
<?php
use Zend\EventManager\StaticEventManager;
use Zend\Mvc\MvcEvent;
use Locale;
$events = StaticEventManager::getInstance();
$events->attach('Zend\Mvc\Application', 'route', function(MvcEvent $event){
$request = $event->getRequest();
$uri = $request->uri();
$baseUrlLength = strlen($request->getBaseUrl() ?: '');
$path = substr($uri->getPath(), $baseUrlLength);
if (preg_match('(/(?P<language>[a-z]{2}))', $path, $match)) {
// Well, you *should* validate the language and compose a real locale at
// this point …
Locale::setDefault($match['language']);
// Update base URL for routing
$event->getRouter()->setBaseUrl($request->getBaseUrl() . $match[0]);
// Make sure that the request path after the base URL still contains at
// least a slash so we do not confuse "home" routes
if (strlen($path) === 3) {
$url->setPath($uri->getPath() . '/');
}
}
}, PHP_INT_MAX);
// Following pseudo code for a view helper for the parts where you need to
// generate URLs to other languages (e.g. language switcher):
public function __invoke($name, array $params, array $options, $language)
{
$router = $this->getRouter();
$baseUrl = $router->getBaseUrl();
// Trim language from base URL if present
if (preg_match('(/(?P<language>[a-z]{2})$)', $path, $match)) {
$newBaseUrl = substr($baseUrl, 0, -3);
} else {
$newBaseUrl = $baseUrl;
}
// Append alternative language to the base URL
if ($language !== 'en') {
$newBaseUrl .= '/' . $language;
}
$router->setBaseUrl($newBaseUrl);
$url = $router->assemble($name, $params, $options);
// Reset base URL
$router->setBaseUrl($baseUrl);
return $url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment