我创建了一个用于过滤产品列表的过滤方法。这是我的网址:
localhost/myshop/products/filter?category=shirts&color=blue&page=1
但是我想这样展示:
localhost/myshop/products/shirts/blue/1
我怎样才能实现它?
最佳答案
假设 Products::filter()
负责处理请求,您可以重写该方法以在其签名中接受参数。所以,如果当前的逻辑是这样的:
class Products extends CI_Controller
{
public function filter()
{
// Retrieve data from GET params
$page = $this->input->get('page');
$color = $this->input->get('color');
$category = $this->input->get('category');
// Do the filtering with $category, $color and $page...
}
}
您可以简单地重构它以通过 URL 段接受参数:
public function filter($category, $color, $page)
{
// Do the filtering with $category, $color and $page...
}
有了这个,您当前的 URL 是:
localhost/myshop/products/filter/shirts/blue/1
我们需要去掉那个额外的 filter/
就完成了,对吧?引用自 docs :
Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. The segments in a URI normally follow this pattern:
example.com/class/method/param1/param2
In some instances, however, you may want to remap this relationship so that a different class/method can be called instead of the one corresponding to the URL.
好的,所以我们需要重新映射当前路线。您有几个选择:
首先,是用新条目更新您的
application/config/routes.php
文件:$route['products/(:any)'] = 'products/filter/$1';
它表示如果 URL 以
products/
开头,则将其重新映射到products
类的filter
方法。在这里您可以使用通配符和正则表达式模式来更加精确地确定您的方法接受的参数类型。
另一种选择是您可能希望实现
_remap()
Controller 中的方法,以便为您进行路由重新映射。
关于php - CodeIgniter 中的 Seo 友好 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40866690/