ci高级用法篇之扩展核心类

来源:互联网 发布:mac桌面上的文件不见了 编辑:程序博客网 时间:2024/05/21 19:49

在上一篇文章ci高级用法篇之创建自己的类库中,你是否觉得每个控制器的构造方法都去执行校验代码其实违背了编程规范中的DRY(do'nt repeat yourself)原则呢?

其实我们完全可以把校验的代码在父类的构造函数中。ci中控制器的父类是CI_Controller,现在我们来扩展这个父类。

在application/core目录下创建一个类文件,MY_Controller.php,内容如下:

<?phpclass MY_Controller extends ci_Controller{public function __construct(){parent::__construct();$this->load->library('auth');$this->auth->checkPower();}}


在将welcome控制器修改为如下版本,让其继承MY_Controller:

<?phpdefined('BASEPATH') OR exit('No direct script access allowed');class Welcome extends MY_Controller {/** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome *- or - * http://example.com/index.php/welcome/index *- or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see http://codeigniter.com/user_guide/general/urls.html */public function __construct(){parent::__construct();}public function index(){$this->load->view('welcome_message');}}
再次访问http://localhost/ci2/,结果出现了同样的报错信息:

非法访问


注意:

①扩展的类必须申明由父类扩展而来.

②新扩展的类所在的文件必须以 MY_ 为前缀(这个选项是可配置的,下面有说明).


如果不喜欢my作为类前缀,可以在application/config/config.php 文件找到这一项修改为除ci_以外的前缀名:

$config['subclass_prefix'] = 'MY_';

0 0