How to use Zend Framework hostname and chain routes to map a module (e.g. admin area) to a different subdomain.

In addition to the standard Static, Route and Regex routes, Zend Framework implements two more less famous – but useful – ones: hostname and chain routes. The first one works with the subdomain (instead of the path) and it can be instantiated with some default parameters (e.g.  “module”=>”admin”). It’s possible to specify a variable in the route, but in my project I’ve specified the few subdomains manually as there were some exceptions to consider.

Each route that needs to be called on the subdomain must be chained separately to its hostname route using the chain route.  The name of the route remains unique in the global space, not in the hostname. That allows to refer a route by name from any part of the application.

Example with module “default” (frontend) and module “admin” (admin area)

How the dispatcher works

  • www.site.com/, the dispatcher will call indexAction of the IndexController of the default module.
  • www.site.com/login, the dispatcher will find the route /login and will load AuthController::logicAction
  • admin.site.com/ dispatches indexAction of IndexController of admin module
  • admin.site.com/login does NOT consider the route “login” as it’s chained to the other hostname, it will dispatch indexAction of LoginController (if exists) of admin module
  • admin.site.com/settings will dispatch indexAction of SettingsController of admin module

How to generate links to routes chained to hostnames (from view scripts, any module):

  • $this->view->url(array(‘controller’=>’aaa’, ‘action’ => ‘bbb’), ‘default’); // will print http://www.site.com/aaa/bbb, even if called from admin area view script
  • $this->view->url(array(), ‘login’); // will print http://www.site.com/login
  • $this->view->url(array(‘controller’=>’aaa’, ‘action’ => ‘bbb’), ‘admin‘); // will print http://admin.site.com/aaa/bbb
  • $this->view->url(array(, ‘adminSettings‘); // will print http://admin.site.com/settings, even if called from a frontend view script

Note: if the name of the route (default, admin, adminSettings, login…) is not specified, the current one will be used. To make a link the the other action of the same controller, you can just use $this->view->url(array(‘ ‘action’ => ‘ccc’));