我正在使用Zend FW 1.9.2,想要禁用默认路由并提供我自己的路由。我真的不喜欢默认的/:controller /:action routing。

这个想法是在init注入路由,当请求无法路由到其中一个注入路由时,它应该被转发到错误控制器。 (通过使用默认的registere Zend_Controller_Plugin_ErrorHandler)

一切正常,直到我使用$ router-> removeDefaultRoutes()禁用默认路由; 当我这样做时,错误控制器不再将未路由的请求路由到错误控制器。相反,它会将所有未路由的请求路由到默认控制器上的indexAction。

任何人都知道如何禁用默认的/:controller /:action routing但是保留路由错误处理?

基本上,这就是我的工作:

$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$router->removeDefaultRoutes(); // <-- when commented, errorhandling works as expected

$route = new Zend_Controller_Router_Route_Static(
    '',
    array('controller' => 'content', 'action' => 'home')
);
$router->addRoute('home', $route);
有帮助吗?

解决方案

删除默认路由时的问题是Zend不再理解urls /:module /:controller /:action,因此无论何时发送路由,它都会路由到默认的Module,index Controller,index Action。

Error插件适用于控制器调度的postDispath方法,它可以工作,因为在标准路由器中如果找不到控制器,模块或操作,则会抛出错误。

要在此配置中启用自定义路由,您必须编写一个适用于preDispatch的新插件,并检查路由,然后在路由无效的情况下重定向到错误插件。

其他提示

删除默认路由时,将删除错误处理程序插件使用的默认路由。这意味着当它尝试路由到

array('module' => 'default, 'controller' => 'error', 'action' => 'index')

您的所有路线都不符合此设置。因此它会失败。我想你可以在默认情况下添加这条路线,如下所示:

$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$router->removeDefaultRoutes(); // <-- when commented, errorhandling works as expected
// Re-add the error route 
$router->addRoute(
   'error', 
    new Zend_Controller_Router_Route (
       'error/:action',
       array (
          'controller' => 'error',
          'action' => 'error'
       )
    )
);

$route = new Zend_Controller_Router_Route_Static(
    '',
    array('controller' => 'content', 'action' => 'home')
);
$router->addRoute('home', $route);

我遇到了一个旧应用程序的相同问题,这就解决了我的问题:

$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$route = new Zend_Controller_Router_Route('*', array('controller'=>'error', 'module'=>'error', 'action'=>'notfound'));
$router->addRoute('default', $route);
// After that add your routes.

您需要先添加此路线,因为它需要是最后一次处理。

在ErrorController中我定义了:

public function notfoundAction()
{
    throw new Zend_Controller_Action_Exception('This page does not exist', 404);
}

这样,任何与我们的路由不匹配的路由都将使用默认的错误处理程序。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top