Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Routing - route subdomains

Tags:

Is there a way to set up hostname based routing in Symfony2?

I didn't find anything about this topic in the official documentation.
http://symfony.com/doc/2.0/book/routing.html

I want to route the request based on the given hostname:
foo.example.com
bar.example.com
{{subdomain}}.example.com

So in essence, the controller would get the current subdomain passed as a parameter.

Similar to the Zend solution:
http://framework.zend.com/manual/en/zend.controller.router.html#zend.controller.router.routes.hostname

$hostnameRoute = new Zend_Controller_Router_Route_Hostname(     ':username.users.example.com',     array(         'controller' => 'profile',         'action'     => 'userinfo'     ) ); $plainPathRoute = new Zend_Controller_Router_Route_Static('');  $router->addRoute('user', $hostnameRoute->chain($plainPathRoute)); 

I hope that it's possible and I just missed it somehow.
Thanks in advance!

like image 521
user523736 Avatar asked Mar 20 '11 01:03

user523736


2 Answers

Just to point out that this is now added in Symfony v2.2 - http://symfony.com/doc/master/components/routing/hostname_pattern.html.

mobile_homepage:     path:     /     host:     m.{domain}     defaults: { _controller: AcmeDemoBundle:Main:mobileHomepage }     requirements:         domain: %domain%  homepage:     path:  /     defaults: { _controller: AcmeDemoBundle:Main:homepage } 
like image 178
Dan Blows Avatar answered Sep 23 '22 03:09

Dan Blows


This is my solution:

In the config.yml inside app dir add the following lines:

services:    kernel.listener.subdomain_listener:        class: Acme\DemoBundle\Listener\SubdomainListener        tags:            - { name: kernel.event_listener, event: kernel.request, method: onDomainParse } 

Then create the class SubdomainListener.php as:

<?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());    } } 
like image 41
Alexander Vasilenko Avatar answered Sep 23 '22 03:09

Alexander Vasilenko