Tips : Find a file in subdirectory with FilterIterator in php

In my previous post Johannes Schlüte leave a comment which recommand me to use a filterIterator. I’m not really familiar with all the SPL capabilities but the best way to improve my knoweldge in SPL is to make test.

So, we have the same subdirectory than is the previus test. Here is the code :

include(dirname(__FILE__)."/class.directorysearch.php");
 
$directory = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(dirname(__FILE__)."/directory",RecursiveDirectoryIterator::KEY_AS_FILENAME));
$search_directory = new DirectorySearchIterator($directory, array("file_to_find.php", "second_file.php"));
 
foreach($search_directory as $test){
  include($search_directory->getPathName());
}

We pass to the DirectorySearchIterator class an instance of an Iterator (here the RecursiveIteratorIterator, but could be and ArrayIterator for example) and an array of values that must be find !

The DirectorySearchIterator extends the FilterIterator. We just have to define an accept method with the valid parameters!

class DirectorySearchIterator extends FilterIterator{    
 
    private
      $files_search;    
 
    public function __construct(Iterator $iterator, array $files){        
 
        parent::__construct($iterator);
        $this->files_search = $files;
 
    }
 
    public function accept(){
 
        return in_array($this->current(),$this->files_search);
    }
 
}

I will make a test with the GlobIterator later…


About this entry