Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^170) CHAPTER 11 ■ SPL FILE AND DIRECTORY HANDLING
■Note You can use a RecursiveFilterIterator for a custom file filter iterator if you want to have the
results in a recursive format. For the example here, the results are presented as a nonrecursive list.
Listing 11-9. Finding All Files of a Specific Type
class FileExtensionFinder extends FilterIterator {
protected $predicate, $path;
public function construct($path, $predicate) {
$this->predicate = $predicate;
$this->path = $path;
$it = new RecursiveDirectoryIterator($path);
$flatIterator = new RecursiveIteratorIterator($it);
parent::
construct($flatIterator);
}
public function accept() {
$pathInfo = pathinfo($this->current());
$extension = $pathInfo['extension'];
return ($extension == $this->predicate);
}
}
$it = new FileExtensionFinder('/path/to/search/','php');
foreach($it as $entry) {
echo $entry. "\n";
}
The accept() method for this class uses the PHP pathinfo function to determine the file’s
extension and accepts any current() entry with the proper file extension. Of course, you can
create filters to search for large files or any other imaginable filtering task.
Creating a Plug-in Directory
It is often desirable to create a plug-in directory where, when files are added, they are loaded
implicitly by the application.
To create a plug-in directory, in which all the code is invoked, you need to feed the results
of a DirectoryIterator into the require_once function. Listing 11-10 shows how you could
accomplish this.
McArthur_819-9C11.fm Page 170 Thursday, February 28, 2008 7:49 AM

Free download pdf