2012-02-23 100 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不会被路由到编辑页面。