2016-03-28 72 views
0

我創建了包含所有crud函數的自定義模型(My_Model)。現在我想在其他模型中繼承該通用模型類。繼承codeigniter中的模型

應用/核心/ My_Model.php

<?php 

class My_Model extends CI_Model { 

protected $_table; 
public function __construct() { 
    parent::__construct(); 
    $this->load->helper("inflector"); 
    if(!$this->_table){ 
     $this->_table = strtolower(plural(str_replace("_model", "", get_class($this)))); 
    } 
} 

public function get() { 
    $args = func_get_args(); 
    if(count($args) > 1 || is_array($args[0])) { 
     $this->db->where($args[0]); 
    } else { 
     $this->db->where("id", $args[0]); 
    } 
    return $this->db->get($this->_table)->row(); 
} 

public function get_all() { 
    $args = func_get_args(); 
    if(count($args) > 1 || is_array($args[0])) { 
     $this->db->where($args[0]); 
    } else { 
     $this->db->where("id", $args[0]); 
    } 
    return $this->db->get($this->_table)->result(); 
} 

public function insert($data) { 
    $success = $this->db->insert($this->_table, $data); 
    if($success) { 
     return $this->db->insert_id(); 
    } else { 
     return FALSE; 
    } 
} 

public function update() { 
    $args = func_get_args(); 
    if(is_array($args[0])) { 
     $this->db->where($args[0]); 
    } else { 
     $this->db->where("id", $args[0]); 
    } 
    return $this->db->update($this->_table, $args[1]); 
} 

public function delete() { 
    $args = func_get_args(); 
    if(count($args) > 1 || is_array($args[0])) { 
     $this->db->where($args[0]); 
    } else { 
     $this->db->where("id", $args[0]); 
    } 
    return $this->db->delete($this->_table);   
} 

} 

?> 

應用/模型/ user_model.php

<?php 

class User_model extends My_Model { } 

?> 

應用/控制器/ users.php

<?php 

class Users extends CI_Controller { 

public function __construct() { 
    parent::__construct(); 
    $this->load->model("user_model"); 
} 

function index() { 

    if($this->input->post("signup")) { 
     $data = array(
       "username" => $this->input->post("username"), 
       "email" => $this->input->post("email"), 
       "password" => $this->input->post("password"), 
       "fullname" => $this->input->post("fullname") 
      ); 
     if($this->user_model->insert($data)) { 
      $this->session->set_flashdata("message", "Success!"); 
      redirect(base_url()."users"); 
     } 
    } 
    $this->load->view("user_signup"); 
} 

} 

?> 

當我加載控制器我得到500內部服務器錯誤,但 如果我取消註釋控制器中的行 - $ this-> load-> model(「user_model」); 那麼該視圖頁面加載,...無法弄清楚發生了什麼... plz幫助..

+0

我在user_model中使用了crud函數......它的工作正常..但是當我把所有的crud函數放在my_model時......它不工作...... my_model沒有在user_model中被繼承.. –

回答

2

在CI配置文件 '的application/config/config.php文件' 找到並設置配置項

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

然後CI load_class函數將加載CI_ModelMy_model當您在例程中調用$ths->load->model('user_model');

+0

它是已經設置... –

+0

它在Windows pc中工作正常..不知道什麼是錯誤的,我的Linux系統 –

+0

感謝您的回答 –