codeigniter模型类的实例

时间:2011-06-13 15:30:12

标签: php codeigniter model instance

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

加载它
$this->load->model('user');

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

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

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

所以,例如我可以

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

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

3 个答案:

答案 0 :(得分:17)

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

所以,如果你想让你的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() );
     }
}

答案 1 :(得分:0)

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

答案 2 :(得分: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);
    }
}