2013-01-17 188 views
0

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

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

因此,在我的路线中,我搜索具有该路线的类别,如果找到它,我想使用controller:forsale和method:get_category。如果它不是一个类别,我会查找子类别,如果我在那里找到它,我想使用controller:forsale和method: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,但我需要一种方法来确定第二块slu is是什么。

最后,可能会有其他网址在使用中,后面跟着(:any)/(:any),所以我需要它能够继续查找其他路线。

回答

1

回答您的问题依次是:
1,而不是使用不同controller#action的,你可以使用一个单一的动作和基于第二蛞蝓(类别或子类别),呈现不同的看法(虽然我不这样的做法,请参阅#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更清晰!

希望它有帮助(我的代码更像是一个psudocode,它没有经过测试)!