带参数和不带参数的 Codeigniter 3 路由
Codeigniter 3 routing with and without a parameter
在以下情况下如何在 Codeigniter 3 中设置路由:
如果我想要所有产品,我使用这个 URL:
https://www.domain.local/product
如果我想展示特定的产品,我使用这个 URL:
https://www.domain.local/product/123
到目前为止,我唯一能让它工作的方法是使用两条单独的路线:
$route['product'] = "Catalog/product";
$route['product/(:any)'] = "Catalog/product/";
如何将这些路线合二为一?我找不到与此相关的文档。
你的方法是正确的方法:
Routes will run in the order they are defined. Higher routes will
always take precedence over lower ones.
和
Route rules are not filters! Setting a rule of e.g. ‘foo/bar/(:num)’
will not prevent controller Foo and method bar to be called with a
non-numeric value if that is a valid route.
在您的控制器函数中,您将检查参数是否存在。
function product($id=0){
if ($id){
// your code for product where id corresponds to (from link)
}else{
// your code if no product id in link
}
}
在以下情况下如何在 Codeigniter 3 中设置路由:
如果我想要所有产品,我使用这个 URL:
https://www.domain.local/product
如果我想展示特定的产品,我使用这个 URL:
https://www.domain.local/product/123
到目前为止,我唯一能让它工作的方法是使用两条单独的路线:
$route['product'] = "Catalog/product";
$route['product/(:any)'] = "Catalog/product/";
如何将这些路线合二为一?我找不到与此相关的文档。
你的方法是正确的方法:
Routes will run in the order they are defined. Higher routes will always take precedence over lower ones.
和
Route rules are not filters! Setting a rule of e.g. ‘foo/bar/(:num)’ will not prevent controller Foo and method bar to be called with a non-numeric value if that is a valid route.
在您的控制器函数中,您将检查参数是否存在。
function product($id=0){
if ($id){
// your code for product where id corresponds to (from link)
}else{
// your code if no product id in link
}
}