模型类

| 我正在使用Codeigniter开发一个网站。现在,通常,当您在codeigniter中使用类时,基本上就好像它是静态类一样使用它。例如,如果我负责一个名为\'user \'的模型,则首先要使用
$this->load->model(\'user\');
而且,我可以在该用户类上调用方法,例如
$this->user->make_sandwitch(\'cheese\');
在我正在构建的应用程序中,我想拥有一个UserManagement类,该类使用一个名为\'user \'的类。 这样,例如我可以
$this->usermanager->by_id(3);
并返回ID为3的用户模型实例。 最好的方法是什么?     
已邀请:
        CI中的模型类与其他语法中的模型类不太一样。在大多数情况下,模型实际上是某种形式的具有数据库层并与之交互的普通对象。另一方面,使用CI时,“ 3”表示数据库层接口,该接口返回通用对象(在某种程度上,它们有点像数组)。我知道,我也撒谎。 因此,如果要使模型返回非4的值,则需要包装数据库调用。 所以,这就是我要做的: 创建一个具有模型类的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() );
     }
}
    
        使用抽象工厂模式或什至可以完成所需工作的数据访问对象模式。     
        
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);
    }
}
    

要回复问题请先登录注册