Symfony2 Locale on subdomains: Not on the url path

Problem:

I have two urls – for example:

en.domain.com 
es.domain.com
yy.domain.com

How I can to set term _locale from url address (en, es, or yy)?

The traditional method is to just rely on the path url for the resource, set a prefix and then let the router automatically set the _locale.

Define a {_locale} prefix on all your routes.

routing_label_exmple:
    resource:  
         "@MyBundle/Resources/config/routing/routing.xml"
    prefix: /{_locale}/somepage

When an url ” /en/somepage ” comes in and matches that route, the _locale “en” is automatically taken from the url, and set.

However with subdomains the challenge is higher. If you want to set the locale from the domain, the solution is to create a listener for the kernel.request event which parses the domain (available using $request->getHost()) to find the locale and then sets the _locale attribute in the request.

This was taken from Stof’s earlier answer to the problem. I am not having time or interest at this time to post the full solution. However I have heard that there is a better way from ornicar as he implemented it on lichess. You should check that out and comment it here. Thanks!

Update:
Here is how it is done from here.

// config.yml
services:
   kernel.listener.subdomain_listener:
       class: Acme\DemoBundle\Listener\SubdomainListener
       tags:
           - { name: kernel.event_listener, event: kernel.request, method: onDomainParse }
 
// SubdomainListener.php
 
<?php
 
namespace Acme\DemoBundle\Listener;
 
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\Event;
 
class SubdomainListener
{
   public function onDomainParse(Event $event)
   {
       $request = $event->getRequest();
       $session = $request->getSession();
 
       // todo: parsing subdomain to detect country
 
       $session->set('subdomain', $request->getHost());
   }
}

2 thoughts on “Symfony2 Locale on subdomains: Not on the url path

  1. Pingback: Symfony2 Subdomain Routing - Different Bundles • PHP Help Coding Programming

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>