Search code examples
phpautoloader

Autoloading both Classes & Models


I know it's common practice to autoload your controllers when using an MVC framework. I have made my own mini-framework where controllers are autoloaded fine.

Are there any security/bad issues with having the same autoload function load the models too?

I.e.

function __autoload($className) { // Autoload both controllers and models.
if(stristr($className, 'Model'))
{
    if (is_readable(Ms . $className . '.php')) {
        include Ms . $className . '.php';
    }
} else {
    if (is_readable(Cs . $className . '.php')) {
        include Cs . $className . '.php';
    }
}
}

Solution

  • You could use namespaces and spl_autoload_register() in order to get such an autoloader. There's no specific security issues regarding a multi autoloader (an autoloader for multi classes of classes) rather than a controller-only autoloader.

    I usually works with namespaces like:

    $home = new controller\home;
    $home->actionIndex();
    
    $users = new model\users;
    
    $post = new view\post;
    

    from there it's easy to replace a \ in the class name with a / to get the specific paths for the file (obviously doing the needed security checking as always).