1

我正在使用 Laravel 开发电子商务。这就是我所坚持的:

这是类别链接的样子:

mysite.com/category_name

mysite.com/category_name [/probable_sub_category_name]

这就是产品链接的样子:

mysite.com/product_name

mysite.com [/probable_category_name] [/probable_sub_category_name] /product_name

我这样设置我的路线:

Route::get(array('(:any)', '(:all)/(:any)'), array('before' => 'is_category', 'uses' => 'categories@index'));
Route::get(array('(:any)', '(:all)/(:any)'), array('before' => 'is_product', 'uses' => 'products@index'));

如果我将产品路线放在首位,则类别链接会中断,如果我将类别路线放在首位,则产品链接会按预期中断。如何为两者使用相同的路由?

我的 PHP 版本是 5.3.10-1ubuntu3.4(说 phpinfo())

4

1 回答 1

3

神奇的是 Controller::call() 方法。这是解决方案:

Route::get(array('(:any)', '(:all)/(:any)'), function () {

    // Current URI as array
    $parameters = Request::route()->parameters;

    // Checks if given parameter is a product's url value
    $check_if_product = function ($parameter) {
        $products = Product::where('url_title', '=', $parameter)->count('id');
        return (is_numeric($products) && $products > 0 ? true : false);
    };

    // Checks if given parameter is a category's url value
    $check_if_category = function ($parameter) {
        $categories = Category::where('url_title', '=', $parameter)->count('id');
        return (is_numeric($categories) && $categories > 0 ? true : false);
    };

    // If last parameter from URI belongs to a product
    if ($check_if_product(end($parameters)))
    {
        return Controller::call('products@index');
    }
    // If last parameter from URI belongs to a category
    elseif ($check_if_category(end($parameters)))
    {
        return Controller::call('categories@index');
    }
    else
    {
        return Response::error('404');
    }

});
于 2013-04-23T15:26:54.110 回答