EllisLab text mark
Advanced Search
     
a helper function to marshall query result to the model
Posted: 09 November 2007 05:04 PM   [ Ignore ]
Joined: 2007-10-22
1 posts

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:

// 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:

// 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