开发者

How to get an array of all sub directories for a specified path?

开发者 https://www.devze.com 2022-12-15 17:49 出处:网络
For example, I have a directory structure like this: my_stuff classes one two more evenmore manymore subsub subsubsub

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 w开发者_高级运维ould I get such an array? Is there some fancy php func for this?


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

  • http://phpkitchen.com/2005/03/advantages-of-using-the-pear-class-naming-convention/
  • http://pear.php.net/manual/en/standards.php
  • http://php.net/manual/en/language.oop5.autoload.php


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.)


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消