2012-02-23 99 views
0

我有一個路線:如何在函數中傳遞參數時正確路由?

Router::connect('/restaurants/*', array('controller'=>'restaurants', 'action' => 'view')); 

,當用戶訪問site.com/restaurants/Seafood,他們得到的海鮮餐館列表。那麼,問題是,現在我想在我的控制器中添加一個編輯功能,並將site.com/restaurants/edit/4路由到我的控制器的視圖功能。如何告訴我的路由發送/餐館/編輯到edit()函數?

我明白貪婪的星星是個壞主意,但我不知道如何讓我的view()函數在沒有它的情況下正常工作。這裏是我的視圖代碼:

public function view($type=null) { 
$this->set('title', $type.' restaurants in and near Gulf Shores'); 
$this->paginate['Restaurant']=array(
    'limit'=>9, 
    'order'=>array(
     'id'=>'asc' 
     ), 
    'joins' => array(
     array( 
      'table' => 'cuisines_restaurants', 
      'alias' => 'CuisinesRestaurant', 
      'type' => 'inner', 
      'conditions'=> array('CuisinesRestaurant.restaurant_id = Restaurant.id') 
     ), 
     array( 
      'table' => 'cuisines', 
      'alias' => 'Cuisine', 
      'type' => 'inner', 
      'conditions'=> array( 
       'Cuisine.id = CuisinesRestaurant.cuisine_id' 
       ) 
      ) 
    ) 
    ); 
$this->set('restaurantType',$this->paginate($this->Restaurant, array('cuisine_type'=>$type))); 

} 

回答

0

如果你有,你需要實現這個功能的控制器數量較少,可以做到「快速「東經髒」的方式,即顯式路由:

Router::connect('/restaurants/edit/*', array('controller'=>'restaurants', 'action' => 'edit')); 

(確保把這個線以上routes.php文件你貪婪的一個)

如果需要此功能,多個控制器和行動,那麼更通用的路由會更有意義。

+0

是的,我已經嘗試過,並且它殺死了/飯店/海鮮(或任何其他餐廳類型)的任何請求。它轉而使用edit()函數。 – huzzah 2012-02-23 21:57:19

+0

我想通了!我的beforeFilter()函數不包括我的任何視圖。你的額外貪婪的明星建議也有助於我的網站安全,所以謝謝! – huzzah 2012-02-23 22:09:36

2

這是做這樣的路線的正確方法:

 
Router::connect(
    '/restaurants/:type', 
    array('controller'=>'restaurants', 'action' => 'view'), 
    array(
     'pass'=>array('type'), 
     'type'=>'regexHere' 
    ) 
); 

Router::connect(
    '/restaurants/edit/:id', 
    array('controller'=>'restaurants', 'action' => 'view'), 
    array(
     'pass'=>array('id'), 
     'id'=>'[0-9]+' 
    ) 
); 

另一種光明的一面,以這種方式是你可以根據正則表達式的路線,因此,如果有人試圖訪問yourwebsite /餐廳/編輯/ notanumber不會被路由到編輯頁面。