Usually, with any decent size site, you are going to run into using subdomains. Whether as static marketing pages or wildcard user domains, it is often necessary to route these subdomains to a particular script in your site.
Zend Framework uses the front controller MVC methodology, which means all pages get routed through index.php. Sure, you could rewrite the subdomain using .htaccess, but you’d lose lose the fancy subdomain URL you crave. So how can you map any subdomain to the proper module / controller / action? Despite the lack of documentation, it is rather easy, with only an update to the preDispatch plugin being required.
The Request Object of Zend Framework provides three very useful methods:
$request->setModuleName(); $request->setControllerName(); $request->setActionName();
With these three methods, you can route to any existing action in your site. For example, let’s say you have the site with three subdomains: about, admin, and fun. Each subdomain has its own module, with its own set of controllers and actions. To route these subdomains to the proper folders, simply do the following in your public function preDispatch of any plugin.
public function preDispatch(Zend_Controller_Request_Abstract $request) { // Split the domain name into parts, assume the structure subdomain.domain.com $urlParts = explode('.', $_SERVER['HTTP_HOST']); $subDomain = $urlParts[0]; $request->setModuleName($subDomain);
See, you are already done. Of course, you’ll want to actually check that the module exists, or if you weren’t using modules, you could route subdomains to different controllers. In a user subdomain scenario, you’d probably route all subdomains to a particular controller and action, like so:
public function preDispatch(Zend_Controller_Request_Abstract $request) { // Split the domain name into parts, assume the structure subdomain.domain.com $urlParts = explode('.', $_SERVER['HTTP_HOST']); $subDomain = $urlParts[0]; if (sizeof($urlParts) === 3 && $subDomain !== 'www') { $request->setControllerName('profiles'); $request->setActionName('view'); // Set the parameter userId to the user in the subdomain // You can get this in the view action with getParam('userId'); $request->setParam('userId', $subDomain); ?>
So that basically covers it. I need to practice being less verbose, but you get the idea.