CI框架不支持像yii2框架那樣,能夠直接在controllers下建立CommonController並繼承父類,那麼咱們想要作登陸控制或權限控制時,直接在父類控制器操做是不合理的。 這時比較方便的方法就是擴展父類的CI_Controller.php
在core目錄下建立一個自定義類,以MY_爲前綴,如MY_Controller,注意這個前綴不能隨意填寫,受到config.php中配置的約束,並讓MY_Controller繼承CI_Controllerhtml
<?php class MY_Controller extends CI_Controller { /** * 後臺登陸控制 * 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; } }
<?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' => '上傳成功']); } $this->load->view("public/title"); $this->load->view("public/menu"); $this->load->view("shopAdd"); } }