【问题标题】:Dynamic routing动态路由
【发布时间】:2012-12-31 23:24:43
【问题描述】:

我希望能够根据从 uri 收集的数据选择控制器。

我有一个类别表和一个子类别表。基本上我有一个以下格式的 URL (:any)/(:any)。第一个通配符是城市 slug(即爱丁堡),第二个通配符将是一个类别或子类别的 slug。

因此,在我的路线中,我使用该路线搜索类别,如果找到,我想使用控制器:forsale 和方法:get_category。如果它不是一个类别,我会查找子类别,如果我在那里找到它,我想使用控制器:forsale 和方法:get_subcategory。如果它不是子类别我想继续寻找其他路线。

Route::get('(:any)/(:any)', array('as'=>'city_category', function($city_slug, $category_slug){
    // is it a category?
    $category = Category::where_slug($category_slug)->first();
    if($category) {    
        // redirect to controller/method
    } 

    // is it a subcategory?
    $subcategory = Subcategory::where_slug($category_slug)->first();
    if($subcategory) {
        // redirect to controller/method
    }
    // continue looking for other routes
}));

首先,我不确定如何在没有实际重定向的情况下在这里调用控制器/方法(因此再次更改 url)。

其次,这甚至是最好的方法吗?我开始使用/city_slug/category_slug/subcategory_slug。但我只想显示city_slug/category|subcategory_slug,但我需要一种方法来判断第二个蛞蝓是哪个。

最后,(:any)/(:any) 后面可能还有其他正在使用的 URL,所以我需要它才能继续寻找其他路由。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    按顺序回答您的问题:
    1. 而不是使用不同的controller#action,您可以使用单个操作并基于第二个 slug(类别或子类别),呈现不同的视图(尽管我不喜欢这种方法,请参阅 #2 和 #3) :

    public class Forsale_Controller extends Base_Controller {
      public function get_products($city, $category_slug) {
        $category = Category::where_slug($category_slug)->first();
        if($category) {    
          // Do whatever you want to do!
          return View::make('forsale.category')->with(/* pass in your data */);
        }
    
        $subcategory = Subcategory::where_slug($category_slug)->first();
        if($subcategory) {
          // Do whatever you want to do!
          return View::make('forsale.sub_category')->with(/* pass in your data */);
        }
      }
    }
    

    2。我认为/city_slug/category_slug/subcategory_slug 比你的方法好得多!你应该和这个一起去!!
    3. 同样,你应该修改你的路线。我总是试图让我的路线不会让我感到困惑,Laravel 也不会!像/products/city/category/subcategory 这样的东西更清楚!

    希望对您有所帮助(我的代码更像是伪代码,尚未经过测试)!

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 1970-01-01
      • 2010-09-22
      • 2016-05-28
      • 2016-02-07
      • 2020-09-07
      • 2012-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多