开发者

Codeigniter - return my model object instead of stdClass Object

Not sure the best way of phrasing this so bear with me.

Within Codeigniter I can return a record set of my object no problem but this is returned as a stdClass object not as an "model" object (for example a Page Object) which I can then use to make use of other methods within that model.

A开发者_开发问答m I missing a trick here? Or is this the standard functionality within CI?


Yes, basically in order for this to work you need to declare your Model objects properties class-wide, and refer to $this being the current model object.

class Blogmodel extends CI_Model {

    var $title   = '';
    var $content = '';   // Declare Class wide Model properties
    var $date    = '';

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }

    function get_entry()
    {
        $query = $this->db->query('query to get single object');
        $db_row = $query->row();            //Get single record

        $this->title   = $db_row->title;
        $this->content = $db_row->content;  //Populate current instance of the Model
        $this->date    = $db_row->date;

        return $this;                       //Return the Model instance
    }
}

I believe get_entry() will return an object type Blogmodel.


You don't need sth like:

$this->title   = $db_row->title;
        $this->content = $db_row->content;  //Populate current instance of the Model
        $this->date    = $db_row->date;

Just put to the result() method ur model:

result(get_class($this));

or

result(get_called_class());

And you'll get instance of ur model!


My solution to this problem consisted of a combination of jondavidjohn's answer and mkoistinen's comment.

According to the CodeIgniter documentation:

You can also pass a string to result() which represents a class to instantiate for each result object (note: this class must be loaded)

Armed with that knowledge, we can rewrite jondavidjohn's solution in this way:

class Blogmodel extends CI_Model {

    var $title   = '';
    var $content = '';   // Declare Class wide Model properties
    var $date    = '';

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }

    function get_entry()
    {
        $query = $this->db->query('query to get single object');
        $blogModel = $query->row('Blogmodel'); //Get single record

        return $blogModel; //Return the Model instance
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜