CI框架扩展自定义控制器的方法

扩展CI中的控制器

有时需要对CI中的控制器作统一操作,如进行登录和权限验证,这时就可以通过扩展CI控制器来实现。

扩展CI控制器只需要在application/core文件夹中建一个继承自CI_Controller类的MY_Controller类即可,然后在这个类中实现自己需要的逻辑。

关于上面这句话,有两点需要解释一下:

1、为什么要在application/core文件夹中:是因为基类CI_Controller是在system/core文件夹中,这里需要跟system中对应。

2、为什么扩展的控制器前缀是MY_,可否换成其他的:这个前缀是在application/config/config.php中定义的:

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

只需要这两处对应上就可以了

二、模型

示例application/models/user_model.php:

<?php
    /**
    * User_model
    */
    class User_model extends CI_Model{

        //return all users
        public function getAll() {
            $res = $this -> db -> get('test');
            return $res -> result();
        }
    }

注意点:

1、文件名全小写

2、类名首字母大写

3、模型中可以使用超级对象中的属性

4、建议用_model作后缀,防止跟其他类名冲突

使用示例:

public function index() {
    //load model
    $this -> load -> model('User_model');
    $usermodel = $this -> User_model -> getAll();

    //别名
    $this -> load -> model('User_model', 'user');
    $usermodel = $this -> user -> getAll();
    var_dump($usermodel);
}

猜你喜欢

转载自www.cnblogs.com/honghebin/p/12322975.html