Ci framework does not support creating CommonController directly under controllers and inheriting the parent class like yii2 framework. When we want to do login control or permission control, it is unreasonable to operate directly on the parent class controller. At this time, the more convenient method is to extend the CI controller of the parent class
1, Create a custom parent controller
Create a user-defined class in the core directory with MY ﹣ as the prefix, such as MY ﹣ controller. Note that this prefix cannot be filled in at will. It is constrained by the configuration in config.php, and let MY ﹣ controller inherit CI ﹣ controller
<?php class MY_Controller extends CI_Controller { /** * Background login control * MY_Controller constructor. */ public function __construct() { parent::__construct(); $this->load->library('session'); if (!isset($this->session->user/isLogin)) { redirect('login/index'); } } public function ajaxReturn($arr) { echo json_encode($arr); die; } }
2, Create custom parent class for controller inheritance
<?php class admin extends My_Controller { public function index() { $this->load->view("public/title"); $this->load->view("public/menu"); $this->load->view("admin"); } public function shopList() { $result = $this->db->select('*')->from('shop_list')->get()->result_array(); $data = []; $data['result'] = $result; $this->load->view("public/title"); $this->load->view("public/menu"); $this->load->view("shopList", $data); } public function addshop() { if ($this->input->post()) { $data = []; $data['name'] = $this->input->post("name"); $data['price'] = number_format($this->input->post("price"), 2); $data['sb'] = $this->input->post("sb"); $data['img_url'] = $this->input->post("img_url"); $data['content'] = htmlspecialchars($this->input->post("content")); $data['content2'] = htmlspecialchars($this->input->post("content2")); $data['content3'] = htmlspecialchars($this->input->post("content3")); $data['create_time'] = date("Y-m-d H:i:s", time()); $this->db->insert("shop_list", $data); $this->ajaxReturn(['status' => 1, 'info' => 'Upload success']); } $this->load->view("public/title"); $this->load->view("public/menu"); $this->load->view("shopAdd"); } }