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

  •, the dispatcher will call indexAction of the IndexController of the default module.
  •, the dispatcher will find the route /login and will load AuthController::logicAction
  • dispatches indexAction of IndexController of admin module
  • 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
  • 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, even if called from admin area view script
  • $this->view->url(array(), ‘login’); // will print
  • $this->view->url(array(‘controller’=>’aaa’, ‘action’ => ‘bbb’), ‘admin‘); // will print
  • $this->view->url(array(, ‘adminSettings‘); // will print, 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’));