模型是专门用来和数据库打交道的PHP类。
例如,假设你想用CodeIgniter来做一个Blog。
你可以写一个模型类,里面包含插入、更新、删除Blog数据的方法。
下面的例子将向你展示一个普通的模型类:
译者注:Blogmodel 这样的命名不符合CodeIgniter的开发规范。
规范的类名命名:Blog_model[code]class Blogmodel extends CI_Model {
var $title = '';
var $content = '';
var $date = '';
function __construct()
{
parent::__construct();
}
function get_last_ten_entries()
{
$query = $this->db->get('entries', 10);
return $query->result();
}
function insert_entry()
{
$this->title = $_POST['title']; // 请阅读下方的备注
$this->content = $_POST['content'];
$this->date = time();
$this->db->insert('entries', $this);
}
function update_entry()
{
$this->title = $_POST['title'];
$this->content = $_POST['content'];
$this->date = time();
$this->db->update('entries', $this, array('id' => $_POST['id']));
}
}[/code]注意: 上面用到的函数是 Active Record 数据库函数。
备注: 为了简单一点,我们直接使用了$_POST。
不过,这不太好,平时我们应该使用 输入类:$this->input->post(‘title’)