模型类的 codeigniter 实例 [英] codeigniter instance of model class

查看:29
本文介绍了模型类的 codeigniter 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 codeigniter 开发一个网站.现在,通常当你在 codeigniter 中使用一个类时,你基本上把它当作一个静态类来使用.例如,如果我领导一个名为user"的模型,我会首先使用

I'm developing a site with codeigniter. Now, normally when you use a class in codeigniter, you basically use it as if it were a static class. For example, if I head a model called 'user', I would first load it using

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

然后,我可以调用该用户类上的方法,例如

and than, I could invoke methods on that user class like

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

在我正在构建的应用程序中,我想要一个 UserManagement 类,它使用一个名为user"的类.

in the application that I'm building, I would like to have one UserManagement class, which uses a class called 'user'.

这样,例如我可以

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

这将返回用户模型的实例,其中 id 为 3.最好的方法是什么?

and this would return an instance of the user model where the id is 3. What's the best way to do that?

推荐答案

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

The model classes in CI are not quite the same thing as model classes in other syntax's. In most cases, models will actually be some form of plain object with a database layer which interacts with it. With CI, on the other hand, Model represents the database layer interface which returns generic objects (they're kinda like arrays in some ways). I know, I feel lied to too.

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

So, if you want to make your Model return something which is not a stdClass, you need to wrap the database call.

所以,这就是我要做的:

So, here's what I would do:

创建一个包含模型类的 user_model_helper:

Create a user_model_helper which has your model class:

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 中:

In 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() );
     }
}

这篇关于模型类的 codeigniter 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆