user1014102
user1014102

Reputation: 345

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:

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.

Upvotes: 10

Views: 888

Answers (1)

igorw
igorw

Reputation: 28249

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;
    }

    ...
}

Upvotes: 7

Related Questions