Codeigniter - return my model object instead of stdClass Object

simnom picture simnom · Mar 3, 2011 · Viewed 7.7k times · Source

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?

Answer

jondavidjohn picture jondavidjohn · Mar 3, 2011

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.