Skip to content

Instantly share code, notes, and snippets.

@Koalabaerchen
Created November 24, 2015 16:45
Show Gist options
  • Save Koalabaerchen/8ed60894cdbbdcd42f3c to your computer and use it in GitHub Desktop.
Save Koalabaerchen/8ed60894cdbbdcd42f3c to your computer and use it in GitHub Desktop.
Locale Sessions in Symfony
<?php
class LocaleListener implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct($defaultLocale = User::DEFAULT_LOCALE)
{
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
if (false === $request->getSession()->isStarted()) {
$request->getSession()->start();
}
// try to see if the locale has been set as a _locale routing parameter
if ($locale = $request->attributes->get('_locale')) {
$request->getSession()->set('_locale', $locale);
} else {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
}
/**
* Returns an array of event names this subscriber wants to listen to.
*
* The array keys are event names and the value can be:
*
* * The method name to call (priority defaults to 0)
* * An array composed of the method name to call and the priority
* * An array of arrays composed of the method names to call and respective
* priorities, or 0 if unset
*
* For instance:
*
* * array('eventName' => 'methodName')
* * array('eventName' => array('methodName', $priority))
* * array('eventName' => array(array('methodName1', $priority), array('methodName2'))
*
* @return array The event names to listen to
*
* @api
*/
public static function getSubscribedEvents()
{
return array(
// must be registered before the default Locale listener
KernelEvents::REQUEST => array(
array(
'onKernelRequest',
17,
),
),
);
}
}
services:
User.localeListener:
class: User\UserBundle\EventListener\LocaleListener
arguments: ["%kernel.default_locale%"]
tags:
- { name: kernel.event_subscriber }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment