Codeigniter路线问题。调用不同的控制器函数取决于传递的参数

时间:2014-09-12 11:04:13

标签: php codeigniter routes

所以,这是我的控制器:

class Catalog extends CI_Controller {

    function index()
    {
        echo "Catalog";
    }

    function view_category($category_slug)
    {
        echo "category_slug = ".$category_slug;
    }

    function view_brand($category_slug, $brand_slug)
    {
        echo "category_slug = ".$category_slug;
        echo "<br>";
        echo "brand_slug = ".$brand_slug;
    }

    function view_product($category_slug, $brand_slug, $product_slug)
    {
        echo "category_slug = ".$category_slug;
        echo "<br>";
        echo "brand_slug = ".$brand_slug;
        echo "<br>";
        echo "product_slug = ".$product_slug;
    }
}

这是我的routes.php:

$route['catalog/(:any)'] = 'catalog/view_category/$1';
$route['catalog/(:any)/(:any)'] = 'catalog/view_brand/$1/$2';
$route['catalog/(:any)/(:any)/(:any)'] = 'catalog/view_product/$1/$2/$3';

但是我传递的参数数量并不重要 - 它总是调用view_category函数。为什么呢?

由于

1 个答案:

答案 0 :(得分:2)

由于所有3条路线的强制性部分(即控制器名称)相同,因此 catalog/ 之后的任何数量的参数将满足,因此无法工作 第一条路线

解决方案可以(未经测试)颠倒您的路线顺序(即按降序排列的参数数量),如下所示。检查它是否有效 -

$route['catalog/(:any)/(:any)/(:any)'] = 'catalog/view_product/$1/$2/$3';
$route['catalog/(:any)/(:any)'] = 'catalog/view_brand/$1/$2';
$route['catalog/(:any)'] = 'catalog/view_category/$1';