Reputation: 7385
What I'm trying to do is access models in the CodeIgniter style, by calling $this->model_name->function()
in my controllers. heres what I've done so far:
$this->load = new Load();
foreach (glob("application/models/*.php") as $file) {
$model = basename($file, ".php");
$this->$model = new $model;
}
I know I can't do what I tried there, but hopefully you can see my objective. What I want to do is make PHP write $this->modelname = new modelname;
for each file in the model folder. I'm grabbing all the PHP files and stripping the directory and .php to leave just the file name.
I apologize if this is hard to understand, its hard to explain >.<
Upvotes: 0
Views: 107
Reputation: 17762
Why not create an autoloader?
spl_autoload_register('customAutoloader');
function customAutoloader($class_name){
$file_name = $class_name . ".php";
//Model
if(substr($class_name, -5) === "Model"){
if(is_readable(PATH_MODELS . $file_name)){
require_once(PATH_MODELS . $file_name);
}
}
}
In this situation, all model classes must be called ModelnameModel, and files should be named the same - ModelnameModel.php and be located in PATH_MODELS.
Upvotes: 1
Reputation: 2050
It actually should work, you just need to actually include the file:
foreach (glob("application/models/*.php") as $file) {
@include_once $file;
$model = basename($file, ".php");
if (class_exists($model)) {
$this->$model = new $model;
} else {
//handle error, trow an exception?
}
}
Upvotes: 1