Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 11 ■ SPL FILE AND DIRECTORY HANDLING^171

Listing 11-10. Creating a Plug-in Directory

$dir = '/path/to/plugins';
$dirit = new DirectoryIterator($dir);

foreach($dirit as $file) {
if(!$file->isDir()) { //Ignore directories, e.g., ./ and ../
require_once($file);
}
}

Instead of loading the files, you could integrate this example with the SPL autoload function-
ality, described in Chapter 9, and factor out any configuration requirements through the use of
naming conventions. This could provide your application with a list of available plug-ins without
any type of implicit installation.

■Note For the most part, you will generally want to use the SPL autoload functionality for loading classes
when the name of the class is known.

Operating on a CVS Directory
Many of you probably have run into CVS version control in your projects. The CVS system creates
a CVS directory and several associated files for every directory that is under revision control.
Sometimes, you may need to perform operations on the contents of a CVS repository, either to
modify permissions or extract information from a CVS checkout.
The NoCvsDirectory filter iterator is included with the SPL examples and provides a way to
filter out these directories from a CVS checkout. You will find this class and an example of how
to use it in nocvsdir.php inside the examples directory. You can find the examples directory at /ext/
spl/examples/ in the PHP source code.

Using Reflection with Directory Iterators
In Chapter 7, you learned about documenting with the reflection API. Using the SPL directory
iterators, you can load all the files in a directory structure. Once they are loaded, you can use
get_declared_classes() (discussed in Chapter 7) to create documentation for an entire
application.

SPL File Object Operations
So far, I’ve talked about how to deal with file and directory names on the file system. The
SplFileObject class takes this concept and allows you to operate on files themselves in a
similar fashion.
The SplFileObject class consolidates the PHP file I/O functions like fopen, fread, and so
on into a versatile, object-oriented interface. You can read and manipulate data using this class

McArthur_819-9C11.fm Page 171 Thursday, February 28, 2008 7:49 AM

Free download pdf