我正在使用CodeIgniter为一个网站编写后端。我希望能够使用这两个网址:(1) website.com/product(返回所有产品的数据)(2) website.com/product/2(返回带有 ID 2 的产品数据)。
我有一个产品控制器,以下是大纲中的相关代码:
class Product extends CI_Controller
public function _remap($id = -1)
{
$this->my_function($id)
}
public function my_function($n)
{
if ($n == -1)
{
// Code to return data on all products
}
else
{
// Code to return specific product data
}
}
我正在使用_remap()
因为没有它,当 URL 的形式为 website.com/product/id 时,代码点火器将希望将 id 解释为一种方法。如果 URL 仅 website.com/product 则 $id 变量的默认值设置为 -1。但奇怪的是,这并没有发生:而是$id设置为字符串"index"(我通过在 _remap() 函数中添加var_dump($id);
来检查这一点)。
这是怎么回事?
我会删除_remap函数。
class Product extends CI_Controller {
function __construct(){
parent::__construct();
}
public function index($id = -1)
{
if($id == -1)
{
echo 'full list';
}
else
{
echo 'work on id' . $id;
}
}
}
然后在config/routes.php
中创建路由
$route['product/(:num)'] = 'product/index/$1';
如果您确实想使用_remap那么您需要执行以下操作:
public function _remap($method, $params = array())
{
if($method == 'index'){
return call_user_func_array(array($this, 'my_function'), $params);
}
}