Home > php教程 > php手册 > body text

CodeIgniter学习笔记三:扩展CI的控制器、模型,codeigniterci

WBOY
Release: 2016-06-13 09:02:17
Original
1024 people have browsed it

CodeIgniter学习笔记三:扩展CI的控制器、模型,codeigniterci

一、扩展CI中的控制器

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

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

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

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

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

<span>$config</span>['subclass_prefix'] = 'MY_';
Copy after login

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

二、模型

示例application/models/user_model.php:

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

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

注意点:

1、文件名全小写

2、类名首字母大写

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

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

使用示例:

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

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

模型主要用于规范项目结构。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!