Code snippets for symfony 1.x


Set user culture from domain name

This filter tries to set the user culture by reading the domain part of the url. I use it for SEO, giving a different domain for each lang of my site.

Add this to your settings.yml :

       fr:   [.net, .fr,]
       it:   []
       en:   [, .com,]

Order is important : first match will assign the corresponding culture.

Create a lib/filters/domainCultureFilter.class.php file :

class domainCultureFilter extends sfFilter
    public function execute($filterChain)
        $user = $this->getContext()->getUser();
        $request = $this->getContext()->getRequest();
        if (!$request->getParameter('sf_culture'))
            if ($user->getAttribute('first_request', true))
                $user->setAttribute('first_request', false);
                foreach ((array)$domainCulture as $culture=>$domains)
                    foreach ((array)$domains as $domain)
                        $pattern = '/'.$domain.'/';
                        if (preg_match( $pattern ,  $_SERVER['HTTP_HOST']) )
                        break 2;
        // Execute next filter

Add the filter to filters.yml :

# insert your own filters here
   class: domainCultureFilter

Comments are very welcome.

by Pierre Bastoul on 2009-04-10, tagged culture  domain  filter 

Comments on this snippet

gravatar icon
#1 Anton Stoychev on 2009-05-01 at 04:04

Neat snippet but to be paranoid you can set the regular expression to :[code php] $pattern = '/'.$domain.'$/';


Cheers for the snippet!

gravatar icon
#2 Guillaume Moigneu on 2009-05-02 at 11:32

The "break 2" command should be inside the preg_match if.

if (preg_match( $pattern , $_SERVER['HTTP_HOST']) ) { $user->setCulture($culture); break 2; }

gravatar icon
#3 Andrzej Skiba on 2009-05-31 at 09:40

Thanks for this great snippet! Since I'm new to Symfony I had no idea how to go about doing this.