4

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

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

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

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

基本上,这就是我所做的:

$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);
4

3 回答 3

4

删除默认路由时的问题是 Zend 不再理解 urls /:module/:controller/:action,所以无论何时发送路由,它都会被路由到默认模块、索引控制器、索引操作。

错误插件在控制器调度的 postDispath 方法上工作,它工作是因为在标准路由器中,如果找不到控制器、模块或动作,它会引发错误。

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

于 2009-09-14T16:03:30.543 回答
0

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

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);
于 2009-09-14T13:13:07.927 回答
-1

我在旧应用程序中遇到了同样的问题,这解决了我的问题:

$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$router->removeDefaultRoutes();
// forward all routes to the not found error action
$route = new Zend_Controller_Router_Route('*', array('controller'=>'error', 'module'=>'error', 'action'=>'notfound'));
$router->addRoute('default', $route);
// After that add your routes.
$route = new Zend_Controller_Router_Route_Static('', array('controller' => 'content', 'action' => 'home'));
$router->addRoute('home', $route);

您需要先添加此路由,因为它需要是最后处理的

在 ErrorController 我定义了:

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

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

于 2016-06-07T20:55:53.807 回答