标签:codeigniter 扩展
在上一篇文章ci高级用法篇之创建自己的类库中,你是否觉得每个控制器的构造方法都去执行校验代码其实违背了编程规范中的DRY(do‘nt repeat yourself)原则呢?
其实我们完全可以把校验的代码在父类的构造函数中。ci中控制器的父类是CI_Controller,现在我们来扩展这个父类。
在application/core目录下创建一个类文件,MY_Controller.php,内容如下:
<?php
class MY_Controller extends ci_Controller{
	public function __construct(){
		parent::__construct();
		$this->load->library('auth');
		$this->auth->checkPower();
	}
}
<?php
defined('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_';
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:codeigniter 扩展
原文地址:http://blog.csdn.net/u011250882/article/details/47065417