CI框架不支持像yii2框架那样,可以直接在controllers下创建CommonController并继承父类,那么我们想要做登录控制或权限控制时,直接在父类控制器操作是不合理的。 这时比较方便的方法就是扩展父类的CI_Controller.
一,创建自定义的父类控制器
在core目录下创建一个自定义类,以MY_为前缀,如MY_Controller,注意这个前缀不能随意填写,受到config.php中配置的约束,并让MY_Controller继承CI_Controller
<?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");
}
}
来源:oschina
链接:https://my.oschina.net/u/4225107/blog/3164900