Autoloading Data Models

Hi Guys

Consider you have a model like this

class samplemodel
{
public method setName(){/*set the name*}
public method setEmail(){/*set the email*}
}

Models are usually relevant to database tables. So if you have tables with 10-12+ fields you may define accessor methods for all these fields in your model. Now when loading data manually in the model after submitting an HTML form you need to call them like this

$model = new samplemodel();
$model->setName(“some name”);
$model->setEmail(“some email”);
……………………..

For models with few accessor methods it may be easy to type manually all these data. But for 10-20-30 its totally ridiculous.

Thats why I designed this small Automatic Data Loader class which takes a model as first argument and and data array as second argument and then loads data from that array to that model. How is it looking?

$val)
{
if (is_callable(array($module,”get{$key}”),$callable))
{
echo “$key
“;
call_user_func(array(&$module,”set{$key}”),$val);
}
}
}
}
?>

Now if you have two input object named “email” and “name” for example in yoru html form and you call this loader as shown below, it will load all the data from $_POST to the model automatically.

$model = new samplemodel();
dataloader::load($model, $_POST);

as the model is accessed with BY_REFERENCE style, so it will fetch $model->setName() and $model->setEmail with appropriate $_POST data and your model will be loaded automatically.

This comes really handy when you have to load models with many accessor methods. I developed this object while working for Bangla Chat Engine last night and Ha Ha HA, it really saves my time.

Caution: Using raw user submitted data from $_POST or $_GET is not secured. You should filter them first.