Valor_ Valor_ - 1 year ago 129
PHP Question

Codeigniter auto autoload models

I wan't to write a function which auto autoloads :) models based on files in folder model. So the application has to scan folder for files, grep all .php files, remove . and .. "folders" and place them in

autoload['model'] = array

This is my current code in autoload.php file

$dir = './application/models';
$files = scandir($dir);
$mods = '';
foreach ($files as $f){
if(glob('*.php') ){
$mods .= str_replace('.php','',"'".$f."',");
$autoload['model'] = $mods;

And i'm keep getting errors like

An uncaught Exception was encountered

Type: RuntimeException

Message: Unable to locate the model you have specified: 'admins','categories','companies','countries'
Filename: D:\wamp64\www\myapp\public_html\rest\system\core\Loader.php

Line Number: 344

It looks like the problem is that when i pass array to $autoload variable it threats whole array as one model. Can you guys help me fix my problem.

Answer Source

I would go for something like:


autoload['model'] = array('autoload_models');


class Autoload_models_model extends CI_Model {

    public function __construct(){


        // Scan directory where this (Autoload_models_model.php) file is located
        $model_files = scandir(__DIR__);

        foreach($model_files as $file){
            // Make sure we are not reloading autoload_models_model
            // Make sure we have a PHP file
               strtolower(explode('.', $file)[0]) !== strtolower(__CLASS__) &&
               strtolower(explode('.', $file)[1]) === 'php')