我创建了一个包含网址为http://somesite.com/controller/function/brand_id/product_id的产品的网站。我想将这些ID更改为更友好的搜索名称。所有这些ID都在DB中,并带有名称。是否可以从数据库中获取这些名称并将其放入URL中?这是因为我无法使用路由工具。产品和品牌是动态的,可以随时删除或(名称)更改。因此,无法将其硬编码到路线中。
感谢您的努力
答案 0 :(得分:1)
您可以使用_remap
Codeigniter内置函数在网址中使用多个函数:
在控制器中使用以下功能:
public function _remap($method){
if ($method == 'project-name')
{
//display project1
}
elseif($method == 'project-name2')
{
//display project2
}
使用params的另一个例子:
public function _remap($method, $params = array())
{
$method = 'process_'.$method;
if (method_exists($this, $method))
{
return call_user_func_array(array($this, $method), $params);
}
show_404();
}
$method
是您网址中的function
:
http://somesite.com/controller/function/brand_id/product_id
您可以通过从数据库中提取它们来为不同的方法执行相同的操作
看看这里:http://codeigniter.com/user_guide/general/controllers.html#remapping
答案 1 :(得分:0)
您应该可以通过为brand_id
和product_id
设置一些通配符路由来完成此操作。在对产品执行查询时,您只需检查URI段是整数(ID)还是字符串(名称),并相应地查询DB。我会存储一个URL友好版本的产品名称(替换空格和特殊字符)然后查询它,并使用它来生成整个应用程序的链接。
更新:以下是您在路由所有内容的方法中所需逻辑的代码示例:
public function search($brand, $product)
{
if (is_int($brand))
{
// Look up the brand using an ID
$this->db->where('id', $brand);
}
else
{
// Look up the brand based on the URI segment
$this->db->where('uri_friendly_name', $brand);
}
// Do the same with adding conditionals for $product and then run the query
}
以下是您需要的路线示例:
$route['controller/function/(:any)/(:any)'] = "controller/search";