Page 1 of 1

Requiring All Files in a Directory

Posted: Sat Aug 15, 2009 2:57 pm
by tecktalkcm0391
Hello,

I have this code so far. I am trying to automatically scan a directory (and sub-directory) and include all files ending in ".actions.php" Right now it will include all of the ones in the main directory, but how can I get it to go into sub-directories?

Thanks!

Code: Select all

<?php
$path = APP_DIR.'actions/';
$dir = dir($path);
while(false !== ($filename = $dir->read())){ 
    if(substr($filename, -12) == '.actions.php') {
        print "$filename\n"; 
        require_once($path.$filename);
    }
}
$dir->close();
?>

Re: Requiring All Files in a Directory

Posted: Sat Aug 15, 2009 3:27 pm
by requinix
You have PHP 5?

Re: Requiring All Files in a Directory

Posted: Sat Aug 15, 2009 3:28 pm
by tecktalkcm0391
Yes, I do have PHP 5.

Re: Requiring All Files in a Directory

Posted: Sat Aug 15, 2009 3:34 pm
by jackpf
I'd use glob() and is_file() or is_dir().

Then, if it's a directory, run the same function on it. Otherwise include it. It could be a bit slow though, depending on how many files you have.

Re: Requiring All Files in a Directory

Posted: Sat Aug 15, 2009 3:37 pm
by tecktalkcm0391
There are quiet a few files, any other suggestions?

Re: Requiring All Files in a Directory

Posted: Sat Aug 15, 2009 3:39 pm
by Eran
use autoload. that is, if you are developing in OOP

Re: Requiring All Files in a Directory

Posted: Sat Aug 15, 2009 9:46 pm
by requinix
__autoload is definitely the best solution if you can use it that way. Thinking specifically about classes, like if the Foo_BarActions class is contained in foo/bar.actions.php: you can break the class name into "Foo" and "Bar" then look for the appropriate file.

Otherwise the SPL is has something for this:

Code: Select all

$dir = new RecursiveDirectoryIterator(APP_DIR . "actions/");
$iterator = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
 
foreach ($iterator as $file => $info) {
    if ($info->isFile() && substr($file, -12) == ".actions.php") include $file;
}

Re: Requiring All Files in a Directory

Posted: Sat Aug 15, 2009 9:52 pm
by tecktalkcm0391
This can work for something else, but I'm calling functions that are contained in the .action.php extention. :( But does autoload pretty much do as it say, and just loads a class only when you need it? Without having to call the function __autoload?

Re: Requiring All Files in a Directory

Posted: Sun Aug 16, 2009 1:44 am
by Cirdan
That's exactly what it does. Also take a look at spl_autoload_register