2016-03-28 132 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

感谢您的回答 –