Question

I need to filter out some files from directory that contains loads of files. During my script this function is called many times.

function getFilteredFiles($criteria) {
    static $files = '';           
    if ($files == '') {
        $files = new DirectoryIterator($path);
    }
    else {
        $files->rewind();
    }

    foreach($files as $file) {
         if (! $file->isDot()) {
             if (!$file->isDir()) {
                  //using $criteria
                  ...
              }
         }
    }
    ...
 }

Is putting the DirectoryIterator in a static variable the way to go to let php only go to the filesystem once to get the files? (= does php only go to the filesystem during the __construct of the DirectoryIterator?)

Was it helpful?

Solution

I looked at the source code, and, it looks like they try to rewind the stream they read the directory entries from, when you rewind the iterator. I don't dare dig into the php streams.c file to look any further, but based on the stream seek I saw, I would guess it doesn't hit the filesystem again.

I guess you could quickly test by using strace.

OTHER TIPS

Is putting the DirectoryIterator in a static variable the way to go to let php only go to the filesystem once to get the files? (= does php only go to the filesystem during the __construct of the DirectoryIterator?)

Yes.

But why did you create a new instance of the data model in the controller instead of subclass it?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top