2011-01-07 245 views
1

這個問題的標題很難提出,它可能不是最好的,無論如何。Zend Framework:如何映射完全動態路由

我有一個區域,類別和供應商的網站,很明顯的解決方案是使用的

"/:module/:controller/:action" 

所以默認路由我的網址會是這個樣子

"/region/midlands/category/fashion" 
"/region/midlands/supplier/ted-baker" 

我想要實現的是這樣的一種URL格式,但是這需要涉及一個數據庫查詢來檢查是否存在midlands,fashionted-baker

"/midlands/fashion" 
"/midlands/ted-baker" 

我原來的解決方案是使用這樣的

"/region/midlands/fashion" 

定義爲

routes.category.route = "/region/:region/:category" 
routes.category.defaults.controller = category 
routes.category.defaults.action = index 
routes.category.defaults.module = default 
routes.category.defaults.category = false 
routes.category.defaults.region = false 

routes.supplier.route = "/supplier/:supplier" 
routes.supplier.defaults.controller = supplier 
routes.supplier.defaults.action = index 
routes.supplier.defaults.module = default 
routes.supplier.defaults.supplier = false 

的路線但是,這意味着與regionsupplier前綴的一切。我幾乎需要用插件徹底劫持請求?

達到此目的的最佳方法是什麼?

感謝您的任何幫助。

編輯。

@ St.Woland,問題是,我想這條路

/:region/:supplier 

要使用此URL

/midlands/ted-baker 

但是這條路線有效地覆蓋了默認路由器

回答

0

我已經使用了ErrorController來做到最後。我在有控制器或無路由的情況下捕獲異常,然後採取相應措施。

對於某些特定路線的數據庫表,有些呼叫是無法找到的,而不是像St.Woland的解決方案那樣獲取所有路線。結果會被緩存使用標籤來幫助很大,這將刪除所有的數據庫查詢查找路線

public function errorAction() 
{ 
    $errors = $this->_getParam('error_handler'); 

    switch ($errors->type) 
    { 
     case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE: 
     case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: 
      //Code for locating routes in Db goes here 
    } 
} 
2

工作最好的方法是像這樣在Bootstrap類中添加一個方法:

<?php 
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap 
{ 
    protected function _initMyRoutes() 
    { 
     // First, initialize Database resource 
     $this->bootstrap('db'); 
     // Second, initialize Router resource 
     $this->bootstrap('router'); 

     // Finally, instantiate your database table with routes 
     $m_routes = new Model_Routes() ; 

     // Now get the Router 
     $router = $this->getResource('router'); 

     // ... and add all routes from the database 
     foreach($m_routes->fetchAll() as $route) { 
      $router->addRoute($route->name, new Zend_Controller_Router_Route($route->path, $route->toArray())) ; 
     } 
    } 
} 

然後在您application.ini

[production] 
bootstrap.path = APPLICATION_PATH/Bootstrap.php 
bootstrap.class = Bootstrap 

這將初始化從數據庫路由路由器。

您應該記住,在每個請求上對數據庫進行排隊並不高效,因此請確保使用緩存。

+0

St.Woland嗨,這個問題是不是與添加的路由。它與我如何最好地處理擁有多條動態路線的能力有關。查看問題編輯。 – 2011-01-07 14:08:22