tags:

views:

61

answers:

3

For example, I have a directory structure like this:

my_stuff
   classes
      one
      two
          more
          evenmore
              manymore
                  subsub
                      subsubsub
          otherstuff
          morestuff
              deepstuff
                  toomuch

and I want to add everything (!) under classes to the php include paths. How would I get such an array? Is there some fancy php func for this?

A: 

Not that I'm aware. As such, you'll have to write your own recursive function that makes use of dir or similar.

However, you'll really want to cache these paths somewhere, as this (to me at least) feels like a needlessly resource intensive activity to carry out for each front end page load. (For example, from what you've said in the past you might only need to re-generate the list of include directories when you change the logic within the CMS, etc.)

Alternatively, you could make items at the intermediate level responsible for including items at lower levels. (This would only really make sense if you were making use of the Factory pattern, etc. which might not be the case.)

middaparka
Starting with PHP 5.1, the real paths of includes and requires are cached by default. See http://prematureoptimization.org/blog/archives/33 - that still doesn't mean the OP should add all the folders to the include path though.
Gordon
+3  A: 

Recursively iterating over a Directory is easy with SplIterators. You just do

$path = realpath('.');

$elements = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path),
    RecursiveIteratorIterator::SELF_FIRST);

foreach($elements as $element){
    // element is an SplFileObject
    if($element->isDir()) { 
        echo "$element\n"; // do whatever
    }
}

However, do not add each directory to your include path.

If you add all these folders to the include path, you will severely slow down your application. If your class is in subsubsub, PHP will first search in my_stuff, then classes, then one, then two and so on.

Instead have your class names follow the PEAR convention and use autoloading.

See

Gordon
A: 
function include_sub_dirs($path) {
    if (!isDirectory($path)) {
        trigger_error("'$path' is not a directory");
    }

    $old = get_include_path();

    foreach (scandir($path) as $subdir) {
        if (!is_directory($subdir)) continue;

        $path .= PATH_SEPARATOR . $path.DIRECTORY_SEPARATOR.$subdir;
        include_sub_dirs($subdir);
    }

    set_include_path($old . PATH_SEPARATOR . $path);

    return true;
}
Kristopher Ives