Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^166) CHAPTER 11 ■ SPL FILE AND DIRECTORY HANDLING
These two functions have an effect on how the getFileInfo(), getPathInfo(), and openFile()
methods operate. It may seem slightly unintuitive that SplFileInfo has a getFileInfo() method;
however, since DirectoryIterator and SPLFileObject descend from SPLFileInfo, this method
provides a way to access information about a specific file in an iterator or downcast a file object
into an info object. The openFile() method will access the file and return an SPLFileInfo object,
which can be used to perform operations within a file, as discussed in the “File Object Operations”
section later in this chapter.


Iteration of Directories


Locating files and directories on disk used to be a somewhat tedious task involving the opendir()
and readdir() functions. Fortunately, now we have the SPL, and instead of interpreting string
values, we have a fully object-oriented interface for working with files. Iteration is a key part in
working with directory structures in the SPL.

Listing Files and Directories


The most basic iterator is DirectoryIterator, which gives you access to a listing of the contents in
a directory. The true power of the SPL starts to emerge when you meet the
RecursiveDirectoryIterator and combine it with the advanced iterator patterns you learned
about in the previous chapter, such as SearchIterator and FilterIterator.

DirectoryIterator
The definition of DirectoryIterator is shown in Listing 11-3.

Listing 11-3. DirectoryIterator Definition

class DirectoryIterator extends SplFileInfo implements Iterator {
function __construct($path) {}
function rewind() {}
function valid() {}
function key() {}
function current() {}
function next() {}
function isDot() {}
function isLink() {}
function __toString() {}
}

The use of this iterator is like that of any other iterator, and it can be exercised with foreach. Its
current() method returns an SplFileInfo object for the current entry in the directory.
Listing 11-4 shows a basic use of DirectoryIterator and SPLFileInfo’s __toString() method.

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

Free download pdf