Thursday, December 11, 2014

Symfony site localization based on domain name

Problem: I want to localize my site based on the domain name.

Symfony strongly suggests that you use paths (like '/en' or '/fr') after the domain name to determine what the locale should be. This is ideal for a site with only one domain name, but for a site that has a different one for each localization, it's unnecessary. You should be able to determine the language based on the domain.

Solution: Use an event listener.

With an event listener, you can catch the request, parse the domain name, and set the locale appropriately. For this blog's purposes, let's say that a site has for its English site and www.frdomain for its French site.

Create this folder/file in your bundle: EventListener/LocaleListener.php. Inside, put this:

namespace My\CustomBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class LocaleListener
  public function setLocale(GetResponseEvent $event)
    if (strstr(strtolower($_SERVER['HTTP_HOST']), strtolower('frdomain')))
      $request = $event->getRequest();


If the HTTP_HOST contains the string 'frdomain', then set the locale to 'fr'.

Now register the listener in your bundle's services.yml file (it should be in Resources/config/). Inside, put this:

        class: My\CustomBundle\EventListener\LocaleListener
            - { name: kernel.event_listener, event: kernel.request, method: setLocale }

Now every time a request is sent to Symfony, this listener runs first and sets the locale to 'fr' if it detects 'frdomain' in HTTP_HOST. Otherwise, it keeps the default locale (in this case, it's en).

That should work! Happy coding!

No comments:

Post a Comment