CodeIgniter 的 Model

基本的 Model 看起來會像這樣。
  1. class Blogmodel extends CI_Model {   
  2.   
  3.     var $title   = '';   
  4.     var $content = '';   
  5.     var $date    = '';   
  6.   
  7.     function __construct()   
  8.     {   
  9.         // 呼叫模型(Model)的建構函數   
  10.         parent::__construct();   
  11.     }   
  12.        
  13.     function get_last_ten_entries()   
  14.     {   
  15.         $query = $this->db->get('entries',10);   
  16.         return $query->result();   
  17.     }   
  18.   
  19.     function insert_entry()   
  20.     {   
  21.         $this->title   = $_POST['title']; // 請看一下下面的注意事項   
  22.         $this->content = $_POST['content'];   
  23.         $this->date    = time();   
  24.   
  25.         $this->db->insert('entries'$this);   
  26.     }   
  27.   
  28.     function update_entry()   
  29.     {   
  30.         $this->title   = $_POST['title'];   
  31.         $this->content = $_POST['content'];   
  32.         $this->date    = time();   
  33.   
  34.         $this->db->update('entries'$this,array('id' => $_POST['id']));   
  35.     }   
  36.   
  37. }  

model 的檔案要放在 application/models/ 下,基本原型為
  1. class Model_name extends CI_Model {   
  2.   
  3.     function __construct()   
  4.     {   
  5.         parent::__construct();   
  6.     }   
  7. }  

Model 需要在 Controller 載入才可以。
  1. $this->load->model('Model_name');  

簡單的 Controller 範例
  1. class Blog_controller extends CI_Controller {   
  2.   
  3.     function blog()   
  4.     {   
  5.         $this->load->model('Blog');   
  6.   
  7.         $data['query'] = $this->Blog->get_last_ten_entries();   
  8.   
  9.         $this->load->view('blog',$data);   
  10.     }   
  11. }  

當 Model 被載入時,並不會自動連結資料庫,不過可以像下面這樣,讓 Model 自動載入
  1. $config['hostname'] = "localhost";   
  2. $config['username'] = "myusername";   
  3. $config['password'] = "mypassword";   
  4. $config['database'] = "mydatabase";   
  5. $config['dbdriver'] = "mysql";   
  6. $config['dbprefix'] = "";   
  7. $config['pconnect'] = FALSE;   
  8. $config['db_debug'] = TRUE;   
  9.   
  10. $this->load->model('Model_name','',$config);  

模型(Models)

留言