codeigniter模型类的实例

big*_*ind 9 php model codeigniter instance

我正在开发一个带有codeigniter的网站.现在,通常在codeigniter中使用类时,基本上就像使用静态类一样使用它.例如,如果我领导一个名为'user'的模型,我会首先使用它来加载它

$this->load->model('user');
Run Code Online (Sandbox Code Playgroud)

而且,我可以调用该用户类的方法

$this->user->make_sandwitch('cheese');
Run Code Online (Sandbox Code Playgroud)

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

所以,例如我可以

$this->usermanager->by_id(3);
Run Code Online (Sandbox Code Playgroud)

这将返回id为3的用户模型的实例.这样做的最佳方法是什么?

cwa*_*ole 17

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

所以,如果你想让你的Model返回一些不是a的东西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.
        */
    }
}
Run Code Online (Sandbox Code Playgroud)

在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() );
     }
}
Run Code Online (Sandbox Code Playgroud)

  • 您无需手动实例化User_model.您可以将模型类名称作为result()的参数传递,它将返回一个填充了DB数据的新实例.`$ Q->结果( 'User_model')` (3认同)