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

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 . "';";
    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.


Theme © iAndrew 2016 - Forum software by © MyBB