CodeIgniter Forums
a helper function to marshall query result to the model - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Libraries & Helpers (https://forum.codeigniter.com/forum-22.html)
+--- Thread: a helper function to marshall query result to the model (/thread-4155.html)



a helper function to marshall query result to the model - El Forum - 11-09-2007

[eluser]Unknown[/eluser]
i started playing around with CI last week and it is a very nice framework. anyway i would like to share a simple helper class that i created to easily marshall the query result to your model

this is my model helper function:

Code:
// model_helper.php

function model_fill($model, $obj) {
    if(sizeof($obj) > 0) {
        foreach($obj as $key=>$value) {
            $phpString = "\$model->" . $key . " = '" . $value . "';";
            eval($phpString);
        }
    }
    
    return $model;
}


this one is the country model class:

Code:
// models/country.php
class Country extends Model {
    
    var $id;
    var $name;
    var $symbol;
    var $code;
    var $default;
    var $disabled;

    function getCountry($countryId) {
        $sql = "SELECT * FROM country WHERE id='". $countryId ."'";
        $query = $this->db->query($sql);
    
        if($query->num_rows() > 0) {
            $row = $query->row();
            [color=red]return model_fill(new Country(), $row);[/color]
        }
        else {
            return null;
        }
    }
}

The highligted text shows how to use the helper method. I just make sure that the name of my column is the same to the name of my model property.


rey