Zend 框架中的主机名和自定义路由对我来说不能一起工作



我正在构建一个应用程序,它使用主机名路由来检测子域,如

user1.example.comuser2.example.com

和自定义路由,如user1.example.com/login

目前为止运行良好,但是当我添加自定义路由时,它们就不起作用了。我已经搜索和阅读了很多,但似乎有一些我错过了。以下是目前为止的内容:

//my routes in routes.ini
[development]
routes.login.type = "Zend_Controller_Router_Route"
routes.login.route = "/login"
routes.login.defaults.controller = "user"
routes.login.defaults.action = "login"

//This part in Bootstrap file
$this->bootstrap('frontController');
$router = $this->frontController->getRouter();
$routerConfig = new Zend_Config_Ini(
    APPLICATION_PATH . '/configs/routes.ini',
    'production'
);
//I create a default route
$routeDefault = new Zend_Controller_Router_Route_Module(
 array(),
 $this->frontController->getDispatcher(),
        $this->frontController->getRequest()
);      
$router->addConfig($routerConfig, 'routes');
// hostname route 
$hostnameRoute = new Zend_Controller_Router_Route_Hostname(
        ':username.mysite.com',
        array(
        'module' => 'default',
        'controller' => 'index',
        'action' => 'index',
        )
      );
//I add the default route.
$router->addRoute('default', $routeDefault);
//I chain the routes so that all routes have subdomain routing too
foreach ($router->getRoutes() as $key => $theroute) {
$router->addRoute($key, $hostnameRoute->chain($theroute));
}

当我去一个自定义路由,如http://user1.example.com/login我得到错误:'无效控制器指定(登录)',这意味着我的自定义路由不被识别。我也不确定我添加默认路由的方式是否正确和必要。如果我删除了代码,它就不能工作了。所以我的问题是,我希望我的主机名匹配,自定义路由和默认路由都能工作。如果你能发现我哪里出错了,请帮助,我已经阅读了以前的相关帖子在路由,链接,默认路由等(包括这个非常相关的一个:我如何在路由INI文件中为Zend框架中的子域编写路由链?),但到目前为止还没有找到解决方案。

你应该能够在路由中使用自定义参数来设置你的路由:

routes.testdynamicsubdomain.type = "Zend_Controller_Router_Route_Hostname"
routes.testdynamicsubdomain.route = ":subdomain.domain.dev"
routes.testdynamicsubdomain.defaults.module = public
routes.testdynamicsubdomain.defaults.controller = index
routes.testdynamicsubdomain.defaults.action = index

如果你的apache/hostfile等配置正确,去test.domain.dev应该在你的indexController中加载索引动作,你可以得到:subdomain参数:

echo $this->getRequest()->getParam('subdomain');

而且,正如你所发现的,路由的顺序非常重要。更多信息请参见Zend Router precedence

相关内容

最新更新