Welcome Guest, Not a member yet? Register   Sign In
a helper function to marshall query result to the model
#1

[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


Messages In This Thread
a helper function to marshall query result to the model - by El Forum - 11-09-2007, 02:04 PM



Theme © iAndrew 2016 - Forum software by © MyBB