2011-06-13 104 views
8

我正在用codeigniter开发一个站点。现在,通常当你在codeigniter中使用一个类时,你基本上使用它,就好像它是一个静态类。例如,如果我头一个名为“用户”的模式,我会首先使用模型类的codeigniter实例

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

,比加载它,我可以在应用程序调用上的用户类的方法,如

$this->user->make_sandwitch('cheese'); 

我'm楼,我想有一个UserManagement类,它使用一个名为'user'的类。

,这样,比如我可以

$this->usermanager->by_id(3); 

,这将返回一个实例的用户模型,其中ID为3 什么是做到这一点的最好办法

+1

最好的办法是使用ORM。 Doctrine很受欢迎,并且有一些教程将它与CodeIgniter – bassneck 2011-06-13 15:37:57

+0

@bassneck thx整合为您的建议。我很可能不会在我目前的项目中使用它,但我一定会研究教义,乍一看看起来很棒。 – bigblind 2011-06-13 17:06:53

回答

16

CI中的模型类与其他语法中的模型类并不完全相同。在大多数情况下,模型实际上是某种形式的普通对象,具有与之交互的数据库层。另一方面,对于CI,Model表示返回通用对象的数据库层接口(它们在某些方面类似于数组)。我知道,我也感到撒谎。

所以,如果你想让你的模型返回一些不是stdClass的东西,你需要包装数据库调用。

所以,这里是我会做什么:

创建具有模型类user_model_helper:

class User_model { 
    private $id; 

    public function __construct(stdClass $val) 
    { 
     $this->id = $val->id; 
     /* ... */ 
     /* 
      The stdClass provided by CI will have one property per db column. 
      So, if you have the columns id, first_name, last_name the value the 
      db will return will have a first_name, last_name, and id properties. 
      Here is where you would do something with those. 
     */ 
    } 
} 

在usermanager.php:

class Usermanager extends CI_Model { 
    public function __construct() 
    { 
      /* whatever you had before; */ 
      $CI =& get_instance(); // use get_instance, it is less prone to failure 
           // in this context. 
      $CI->load->helper("user_model_helper"); 
    } 

    public function by_id($id) 
    { 
      $q = $this->db->from('users')->where('id', $id)->limit(1)->get(); 
      return new User_model($q->result()); 
    } 
} 
+0

真棒,thx男人! – bigblind 2011-06-13 17:07:26

+3

您不需要手动实例化User_model。您可以将模型类名作为result()的参数传递,并且它将返回一个填充了数据库中数据的新实例。 '$ Q->结果( 'User_model')' – jfadich 2015-11-05 18:12:10

0

使用抽象工厂模式甚至数据访问对象模式来完成您需要的工作。

0
class User extend CI_Model 
{ 
    function by_id($id) { 
     $this->db->select('*')->from('users')->where('id', $id)->limit(1); 
     // Your additional code goes here 
     // ... 
     return $user_data; 
    } 
} 


class Home extend CI_Controller 
{ 
    function index() 
    { 
     $this->load->model('user'); 
     $data = $this->user->by_id($id); 
    } 
}