Although PHP was originally conceived as a procedural language, object-oriented features have been incorporated into every major release going all the way back to version 3. Offering a compliment of features such as
interfaces,
namespaces, and
inheritance, developers hailing from other object-oriented languages such as Java and C++ can quickly adapt to PHP with little trouble.
Indeed, object-oriented programming (OOP) has become so pervasive within the PHP community that many choose to employ the approach at every opportunity. One great way to incorporate more OOP into your applications is through the
Standard PHP Library (SPL), a powerful yet largely unknown extension made part of the official PHP language with the PHP 5.0 release. The SPL provides a series of classes which extend the PHP language in numerous ways, offering object-oriented
advanced data structures,
iterators, and
file handlers, among other features.
In this tutorial I'll introduce you to several of my favorite SPL iterators, providing you with the basis from which you can continue your own exploration. Following several examples, I'll conclude with a brief introduction to other key SPL features.
Introducing SPL Iterators (in PHP 5)
The SPL provides over 20 classes useful for iterating over and manipulating different types of data, including arrays, directories, files, and XML. For instance the
ArrayIterator class is useful for interacting with arrays. Consider for instance the following array:
$platforms = array('Nintendo DS', 'PlayStation 2', 'PlayStation 3');
You can use the ArrayIterator class to work with the $platforms array in a strictly object-oriented fashion:
$platforms = array('Nintendo DS', 'PlayStation 2', 'PlayStation 3');
// Load the array into an array object
$platformArray = new ArrayObject($platforms);
// Append a new platform to the end of the array
$platformArray->append('Xbox 360');
// Determine the array size
printf("Tracking %d platforms:
", $platformArray->count());
// Iterate over the array, outputting each array element
for($i = $platformArray->getIterator(); $i->valid(); $i->next())
{
printf("%s
", $i->current());
}
Executing this snippet produces the following output:
Tracking 4 platforms:
Nintendo DS
PlayStation 2
PlayStation 3
Xbox 360
Iterating Over a Filesystem Directory with DirectoryIterator
Several recent projects have involved interaction with the server's file system, including using PHP to learn more about how many images reside in a specific directory. You can use the SPL's
DirectoryIterator class to easily navigate a directory, to learn more about the files, file permissions, and file owners, among other things. Consider a directory named
images, which contains the following five images:
house.png,
icon.gif,
logo.jpg,
truck.png and
vacation.png. The following snippet can be used to parse this directory in order to determine how many different file types exist:
<!--p
$extensions = array();
// Iterate over a directory named images
foreach (new DirectoryIterator('images') as $fileInfo) {
// If the iterator is placed atop . or .., continue
if($fileInf-->isDot()) continue;
// Use the pathinfo() function to parse the file name
$file = pathinfo($fileInfo->getFilename());
// We only want the file extension
$extension = $file['extension'];
// Determine if the extension name is already being tracked
// in the $extensions array. If so, increment the associated
// value. Otherwise, add the extension to the array.
if (array_key_exists($extension, $extensions))
{
$extensions[$extension]++;
} else {
$extensions[$extension] = 1;
}
}
var_dump($extensions);
?>
Executing this snippet produces the following results (formatted for readability):
array
'png' => int 3
'gif' => int 1
'jpg' => int 1
Iterating Over XML with SimpleXMLIterator
Manipulating XML has been a notoriously difficult task, one which was greatly simplified with the introduction of PHP's
SimpleXML extension. The
SimpleXMLIterator class builds upon the SimpleXML extension's strengths, adding several new powerful capabilities to an already amazing feature. Consider the following Docbook-formatted file:
When using the date() function, you must
provide at least one input parameter.
Suppose you wanted to parse this file in order to analyze the frequency in which code and glossary terms are referenced within the text. You can use the SimpleXMLIterator to easily examine the file:
<!--p
// Read the XML file into the SimpleXmlIterator object
$chapter = new SimpleXmlIterator('chapter.docbook', 0, TRUE);
// Iterate over the file, and if an element contains children,
// output information about the child key and value
for($chapte-->rewind(); $chapter->valid(); $chapter->next() ) {
foreach($chapter->getChildren() as $name => $data) {
echo "{$name}: {$data}
";
}
}
?>
Executing this snippet produces the following output:
code: date()
emphasis: must
glossterm: input parameter
Beyond Iterators: Other SPL Features
Iterators are only one part of what the SPL has to offer. Be sure to check out these other great features:
- Advanced Data Structures: The SPL offers several advanced data structures, including heaps, stacks, queues, doubly linked lists, and a fixed array.
- Exceptions: The SPL offers 13 context-specific exceptions useful for further clarifying the intent of your code. Examples of custom exceptions include
LengthException, LogicException, OverflowException and RuntimeException.
- File Handling: You can use the SPL's file handling classes to uncover a great deal of information about system files, the path, modification timestamp, creation timestamp, owner, and much more.
Conclusion
Are you using the SPL in interesting ways? Tell us how in the comments!
About the Author
Jason Gilmore is founder of the publishing, training, and consulting firm WJGilmore.com. He is the author of several popular books, including "Easy PHP Websites with the Zend Framework", "Easy PayPal with PHP", and "Beginning PHP and MySQL, Fourth Edition". Follow him on Twitter at @wjgilmore.