我有一个名为Collection
的类,它具有两个名为Index
和Cars
的方法。
在我的控制器的基本格式中,它看起来像这样;
class Collection extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
}
public function index(){
$data = array(
'title' => 'Index Page'
);
$this->load->view('template/Header');
$this->load->view('collection/index', $data);
$this->load->view('template/Footer');
}
public function cars(){
$data = array(
'title' => 'Cars Page'
);
$this->load->view('template/Header');
$this->load->view('collection/list_of_cars', $data);
$this->load->view('template/Footer');
}
}
URI看起来像这样;
example.com/collection/cars
这完成了我想要的操作,处理了cars
方法,并且像往常一样显示了list_of_cars
视图。
但是我注意到,如果我在URL中添加另一个参数,例如
example.com/collection/cars/something
实际上,我可以根据需要添加尽可能多的其他URI参数,但仍然不会出现404错误。
该页面只是重新加载-因为该页面不存在,它是否应该不显示404错误?
任何建议都值得赞赏。
答案 0 :(得分:1)
如果您的URI包含两个以上的段,它们将作为参数传递给您的方法。
您给出的细分被视为您正在访问的方法的参数,表示您是否这样给出
example.com/collection/cars/something
您可以像这样
在您的cars方法中访问此参数public function cars($param)
{
echo $param;
}
如果你这样给我
example.com/collection/cars/something/testing
您可以像这样
在您的cars方法中访问此参数public function cars($param,$param2)
{
echo $param;
echo $param2;
}
更新:
如果要基于段进行某些检查,请在方法中使用$this->uri->segment()
,如下所示:
if ($this->uri->segment(3) === FALSE)
{
/*this is your error page*/
$this->load->view('error-page');
}
else
{
$arg = $this->uri->segment(3);
}
更多信息:https://www.codeigniter.com/user_guide/libraries/uri.html
一种类似的方法可以构造如下。如果有两个以上的段(即控制器+方法),则存在参数,因此强制使用404。
if ($this->uri->total_segments() > 2)
{
show_404(); //shows 404 page, logs the error, and ends execution
}
了解show_404()
here。