« Return to Thread: map domain name to module

Re: map domain name to module

by Ivan Shumkov :: Rate this Message:

Reply to Author | View in Thread

Michael Depetrillo wrote:
Has anyone written any code to map a domain name to a specific module? I would like to be able to have a admin-specific-domain.com parked on top of my application and then route all requests to the admin module.

Small modification of code:

$frontController = Zend_Controller_Front::getInstance();
$frontController->setControllerDirectory(array('default' => '../controllers/',
							   'admin' => '../admin/controllers/'));

$router = new Zend_Controller_Router_Rewrite();
$router->removeDefaultRoutes();

$router->addRoute('default', new SmartShop_Controller_Router_DefaultSubdomainRoute(
    array(),
    $frontController->getDispatcher(),
    $frontController->getRequest()
));

foreach ($config->routes as $route) {
    $router->addRoute(
	   $config->routes->key(),
	   new SmartShop_Controller_Router_SubdomainRoute(
	        $route->url,
	        $route->defaults? $route->defaults->asArray() : null,
	        $route->requirements? $route->requirements->asArray() : null
	  )
    );
}

$frontController->setRouter($router);
$frontController->dispatch();


class SmartShop_Controller_Router_SubdomainRoute extends Zend_Controller_Router_Route
{
    function match($path)
    {
        $module = SmartShop_Uri_Http::getCurrentSubdomain();
        if (!$module) $module = 'default';

        // if subdomain is listed in requirements, check for match
        if(isset($this->_requirements['module']) &&
           $module != $this->_requirements['module']
        ) {
            return false; // this route failed
        }

        $params = parent::match($path);
        if ($params) {
            $params['module'] = $module;
        }

        return $params;
    }
}

class SmartShop_Controller_Router_DefaultSubdomainRoute extends Zend_Controller_Router_Route_Module
{
    function match($path)
    {
        $module = SmartShop_Uri_Http::getCurrentSubdomain();

        if ($module && !$this->_dispatcher->isValidModule($module)) {
            return false;
        }

        $params = parent::match($path);
        if ($params && $module) {
            $params[$this->_moduleKey] = $module;
        }

        return $params;
    }
}

class SmartShop_Uri_Http
{
    public static function getCurrentSubdomain()
    {
        // get subdomain
        $subdomains = explode('.', $_SERVER['HTTP_HOST']);
        $countSubdomains = count($subdomains);
        if ($countSubdomains == 2 || ($countSubdomains == 3 && $subdomains[0] == 'www')) {
            $subdomain = false;
        } else if ($subdomains[0] == 'www') {
            $subdomain = $subdomains[1];
        } else {
            $subdomain = $subdomains[0];
        }

        return $subdomain;
    }
}

 « Return to Thread: map domain name to module