【问题标题】:How to route correctly when an argument is passed in a function?在函数中传递参数时如何正确路由?
【发布时间】:2012-03-14 07:19:40
【问题描述】:

我有一条路线:

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

当用户访问 site.com/restaurants/Seafood 时,他们会获得一份海鲜餐厅列表。好吧,问题是,现在我想在我的控制器中添加一个编辑功能,并且 site.com/restaurants/edit/4 路由到我的控制器的视图功能。如何告诉我的路线将 /restaurants/edit 发送到 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)));

}

【问题讨论】:

    标签: cakephp routes cakephp-2.0


    【解决方案1】:

    如果您需要实现此功能的控制器数量较少,您可以使用“quick 'n dirty”方式,即显式路由:

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

    (确保将这一行放在您在 routes.php 中的贪婪行之上)

    如果您需要为许多控制器和操作提供此功能,那么更通用的路由会更有意义。

    【讨论】:

    • 是的,我已经试过了,它会终止对 /restaurants/Seafood(或任何其他餐厅类型)的任何请求。它改为路由到 edit() 函数。
    • 我想通了!我的 beforeFilter() 函数不包括我的任何观点。你额外的贪婪星建议也有助于我的网站安全,所以谢谢你!
    【解决方案2】:

    这是进行这样的路由的正确方法:

    路由器::连接( '/餐厅/:类型', 数组('控制器'=>'餐厅','动作'=>'视图'), 大批( '通过'=>数组('类型'), 'type'=>'regexHere' ) ); 路由器::连接( '/restaurants/edit/:id', 数组('控制器'=>'餐厅','动作'=>'视图'), 大批( '通过'=>数组('id'), 'id'=>'[0-9]+' ) );

    这种方式的另一个亮点是您可以根据正则表达式进行路由,因此如果有人试图访问您的网站/餐厅/编辑/notanumber,将不会被路由到编辑页面。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      • 2016-09-30
      • 2021-08-13
      • 1970-01-01
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多