Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Language for TLD

I'm new in Symfony2 and I'm looking for choose the language with the TLD of my hostname. (in a proper way)

I already find some way to change the language with a form: http://symfony.com/blog/play-with-the-user-language

But I need to be able to select the language when a new user connect with:

  • www.hostname.fr => fr
  • www.hostname.it => it
  • www.hostname.co.uk => en

For now I add a service listener that trigger for each request:

services:
    kernel.listener.domain_langue_listener:
        class: acme\DemoBundle\Listener\DomainLangueListener
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onDomainParse }

With the class:

namespace acme\DemoBundle\Listener;
class DomainLangueListener
{
    public function onDomainParse(Event $event)
    {
        $request = $event->getRequest();
        $session = $request->getSession();

        preg_match('/[^.]+$/', $request->getHost(), $match);
        $session->setLocale($match[0]);
    }
}

This Listener works but I would like to use some Parameters to define which TLD match with which Language, But in the Listener I cannot access to the container like that:

$this->container->getParameter('tld_allowed');

I would like to know if there is another way to access to Parameters in a Listener Or an other way to select a language with the hostname

Thanks for your answers.

like image 396
user1014102 Avatar asked Oct 26 '11 08:10

user1014102


1 Answers

You're almost there. The only thing you have to do now is inject the parameters into your listener, using "arguments" (arguments for the constructor). %foobar% refers to the "foobar" parameter, @foobar refers to the "foobar" service.

parameters:
    tld_allowed: en,fr,de

services:
    kernel.listener.domain_langue_listener:
        class: acme\DemoBundle\Listener\DomainLangueListener
        arguments:
            - %tld_allowed%
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onDomainParse }

And the listener:

namespace acme\DemoBundle\Listener;
class DomainLangueListener
{
    public function __construct($tldAllowed)
    {
        $this->tldAllowed = $tldAllowed;
    }

    ...
}
like image 180
igorw Avatar answered Oct 26 '22 20:10

igorw