2009-09-14 132 views
4

我使用Zend FW 1.9.2,想要禁用默認路由並提供我自己的。我真的不喜歡默認的/:controller /:action routing。Zend框架:刪除默認路由

這個想法是在init中注入路由,並且當請求不能被路由到一個注入路由時,它應該被轉發到錯誤控制器。 (通過使用默認註冊Zend_Controller_Plugin_ErrorHandler)

這一切工作正常,,直到我禁用默認路由$ router-> removeDefaultRoutes(); 當我這樣做時,錯誤控制器不再將未路由的請求路由到錯誤控制器。相反,它將所有未路由的請求路由到默認控制器上的indexAction。

任何人都有任何想法如何禁用默認/:控制器/:行動路由但保持路由錯誤處理?

基本上,這是我做的:

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

回答

5

時刪除默認路由是Zend公司不再理解的網址/問題:模塊/:控制器/:動作,所以每當路由被髮送,它被路由到默認模塊,索引控制器,索引操作。

錯誤插件在控制器調度的postDispath方法上工作,它的工作原理是因爲在標準路由器中如果沒有找到控制器或模塊或操作,它會引發錯誤。

要在此配置中啓用自定義路由,您必須編寫一個適用於preDispatch的新插件,並檢查路由,然後在發生無效URL時重定向到錯誤插件。

+0

謝謝,這是有道理的,我會測試它。 – Maurice

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); 
+0

我檢查了,但默認錯誤處理插件沒有注入任何路由,所以刪除默認路由應該(理論上)對它沒有影響。 我試着添加一個像你一樣的錯誤路由,但沒有改變它的工作方式。說實話,我真的不認爲你的答案是有道理的,因爲這隻會匹配/ error/asd和/ error/qwe等請求。 我錯過了什麼嗎? – Maurice

-1

我遇到了同樣的問題,一箇舊的應用程序,這裏是解決我的問題:

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

這種方式不匹配我們的路線將使用默認的錯誤處理程序的路由。