Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get class object with $query->row on Codeigniter

I'm currently working with the Codeigniter framemwork. In the code below, I would like to get an Animal_model object, not a stdClass Object.

<?php
class Animal_model extends CI_Model{

    var $idanimal;
    var $name;
    public static $table = 'animals';

    function __construct() {
        parent::__construct();
    }

    function getone(self $animal){
        $query = $this->db->get_where(self::$table, array('id_animal' => $animal->idanimal));

        if($query == FALSE){
            return FALSE;
        }else{
            return $query->row(); // How to get an Animal_model object here? 
        }
    }
}

$lion = new Animal_model();
$lion->idanimal = 25; 
var_dump($lion); // It says "object(Animal_model)".

$lion = $lion->getone($lion);
var_dump($lion); // Now it says "object(stdClass)".

?>

How to convert $query->row() to an Animal_model object?

like image 444
Dacobah Avatar asked Dec 17 '12 14:12

Dacobah


2 Answers

CodeIgniter has built-in functionality for this!

return $query->row(0, 'Animal_model');
like image 142
Oscar Broman Avatar answered Oct 04 '22 21:10

Oscar Broman


    if($query == FALSE){
        return FALSE;
    }else{
       // How to get an Animal_model object here? 
       $row = $query->row();

       $animal = new Animal_model();
       $animal->idanimal = $row->idanimal;
       $animal->name= $row->name;
       return $animal;
    }

The above will do what you want but I don't think it's a very good idea. It would be better to have a second class such as Animal which doesn't extend any model that you can use to represent an animal.

class Animal
{
    public name = '';
    public id = 0;

    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }
}

In your model, you can create instances of this and return them, instead of returning model objects.

    if($query == FALSE){
        return FALSE;
    }else{
        $row = $query->row();
        return new Animal($row->idanimal, $row->name);
    }

I would also change the getone function to take an ID instead, and select where this ID matches:

function getone($id){

This way you use the model as a manager for the animals, the model deals with the data and returns Animal objects.

like image 35
MrCode Avatar answered Oct 04 '22 20:10

MrCode