CodeIgniter Forums
__autoload - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: __autoload (/showthread.php?tid=12019)



__autoload - El Forum - 10-02-2008

[eluser]Moon 111[/eluser]
I would like to create an __autoload function. Where should I put it?


__autoload - El Forum - 10-02-2008

[eluser]Moon 111[/eluser]
I'm thinking of creating a presystem hook?


__autoload - El Forum - 10-02-2008

[eluser]Rick Jolly[/eluser]
Good question. I don't know what the most logical place would be. Obviously, an autoload function could be in any file that is included before the classes you wish to autoload. A hook is a fine solution if you are planning to use the autoload in all your applications (a system extension rather than an application-specific extension). The simplest method would be to put the autoload in index.php or config.php, but I'm not sure if that's the most logical or transparent place.


__autoload - El Forum - 10-02-2008

[eluser]Moon 111[/eluser]
Quote:A PHP Error was encountered
Severity: Warning

Message: include(C:\wamp\www\CodeIgniter/system/application/models/ci_db.php) [function.include]: failed to open stream: No such file or directory

Filename: codeigniter/CodeIgniter.php

Line Number: 193

I put it where it would call the pre_controller hooks...

What's wrong?


__autoload - El Forum - 10-02-2008

[eluser]Moon 111[/eluser]
I updated so that it ignored anything that couldn't be found in the models folder.

Code:
<?php

function __autoload($classname) {

    $handle = opendir(APPPATH . 'models/');
    
    while (false !== ($file = readdir($handle))) {
        $file_array[] = $file;
    }
    
    if(in_array(strtolower($classname) . '.php', $file_array))
        include APPPATH . 'models/' . strtolower($classname) . '.php';
}

?>



__autoload - El Forum - 10-02-2008

[eluser]Rick Jolly[/eluser]
That's terribly inefficient. Use naming conventions instead. If only models have the word "Model" in their name, then:
Code:
if(stristr($classname,'model'))
{
    require_once(APPPATH . 'models/' . $classname . EXT);
}