Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Am I missing a trick here? Or is this the standard functionality within CI?

like image 964
simnom Avatar asked Mar 03 '11 14:03

simnom


1 Answers

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.

like image 156
jondavidjohn Avatar answered Oct 13 '22 04:10

jondavidjohn