模型的加载

什么是模型?
模型是专门和数据库打交道的PHP类。 假设你使用 CodeIgniter 管理一个博客,那么你应该会有一个用于插入、更新以及获取博客数据的模型类。 这里是一个模型类的例子:php

class Blog_model extends CI_Model {

    public $title;
    public $content;
    public $date;

    public function get_last_ten_entries()
    {
        $query = $this->db->get('entries', 10);
        return $query->result();
    }

    public function insert_entry()
    {
        $this->title    = $_POST['title']; // please read the below note
        $this->content  = $_POST['content'];
        $this->date = time();

        $this->db->insert('entries', $this);
    }

    public function update_entry()
    {
        $this->title    = $_POST['title'];
        $this->content  = $_POST['content'];
        $this->date = time();

        $this->db->update('entries', $this, array('id' => $_POST['id']));
    }

}

注解html

注解:为了保证简单,咱们在这个例子中直接使用了 $_POST 数据,这实际上是个很差的实践, 一个更通用的作法是使用 输入库  $this->input->post('title')数据库

剖析模型

模型类位于你的 application/models/ 目录下,若是你愿意,也能够在里面建立子目录。app

 

模型类的基本原型以下:ide

class Model_name extends CI_Model {

    public function __construct()
    {
        parent::__construct();
        // Your own constructor code
    }

}

其中,Model_name 是类的名字,类名的第一个字母 必须 大写,其他部分小写。确保你的类 继承 CI_Model 基类。codeigniter

文件名和类名应该一致,例如,若是你的类是这样:post

class User_model extends CI_Model {

    public function __construct()
    {
        parent::__construct();
        // Your own constructor code
    }

}

那么你的文件名应该是这样:ui

application/models/User_model.php

加载模型

你的模型通常会在你的 控制器 的方法中加载并调用, 你能够使用下面的方法来加载模型:this

$this->load->model('model_name');

若是你的模型位于一个子目录下,那么加载时要带上你的模型所在目录的相对路径, 例如,若是你的模型位于 application/models/blog/Queries.php , 你能够这样加载它:spa

$this->load->model('blog/queries');

加载以后,你就能够经过一个和你的类同名的对象访问模型中的方法。

$this->load->model('model_name');

$this->model_name->method();

若是你想将你的模型对象赋值给一个不一样名字的对象,你能够使用 $this->load->model() 方法的第二个参数:

$this->load->model('model_name', 'foobar');

$this->foobar->method();

这里是一个例子,该控制器加载一个模型,并处理一个视图:

class Blog_controller extends CI_Controller {

    public function blog()
    {
        $this->load->model('blog');

        $data['query'] = $this->blog->get_last_ten_entries();

        $this->load->view('blog', $data);
    }
}
相关文章
相关标签/搜索