codeigniter instance of model class

﹥>﹥吖頭↗ 提交于 2019-12-03 02:58:42

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.

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:

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.
        */
    }
}

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

Use abstract factory pattern or even Data access object pattern which does the job that you require.

Didozavar
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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!