Valor_
Valor_

Reputation: 3591

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);
unset($files[0]);
unset($files[1]);
$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.

Upvotes: 1

Views: 4869

Answers (3)

antelove
antelove

Reputation: 3348

/* autoload model */
function iteratorFileRegex( $dir, $regex )
{

    $files = new FilesystemIterator( $dir );
    $files = new RegexIterator( $files, $regex );

    $models = array();

    foreach ( $files as $file )
    {
        $models[] = pathinfo( $file, PATHINFO_FILENAME ); // Post_Model
    }

    return $models;

}

$autoload['model'] = iteratorFileRegex( APPPATH . "models", "/^.*\.(php)$/" );

Upvotes: 1

Valor_
Valor_

Reputation: 3591

This is the solution that worked for me. If you find any shorter or nicer code please let me know

$dir    = './application/models';
$files = scandir($dir);
$models = array();
foreach ($files as $f){
    $file_parts = pathinfo($f);
    $file_parts['extension'];
    $correct_extension = Array('php');
    if(in_array($file_parts['extension'], $correct_extension)){
        array_push($models, str_replace('.php','',$f));
    }
}
$autoload['model'] = $models;

Upvotes: 1

MonkeyZeus
MonkeyZeus

Reputation: 20747

I would go for something like:


/application/config/autoload.php

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

/application/models/Autoload_models_model.php

class Autoload_models_model extends CI_Model {

    public function __construct(){

        parent::__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
            if(
               strtolower(explode('.', $file)[0]) !== strtolower(__CLASS__) &&
               strtolower(explode('.', $file)[1]) === 'php')
            {
                $this->load->model(strtolower($file));
            }
        }
    }
}

Upvotes: 1

Related Questions