Main Methods of the DirectoryIterator Class in PHP 5

The DirectoryIterator class is an important part of the Standard PHP Library (SPL). Among other things, it lets you traverse any specified directory with a regular “foreach” loop. In this first article of a three-part series, some of the most relevant methods that come with the “DirectoryIterator” class are covered.

Introduction

During your productive life as PHP developer, you’ve quite possibly found yourself “reinventing the wheel” many times, particularly in those cases where you needed to develop certain modules of an application from scratch. Yeah, I know what this means, since I’ve done the same thing frequently, and it often happens that one doesn’t feel confident enough to delegate the control and programming of the application to third-party software packages.

Even now, when things are radically different (at least to me), since I’m using well-trusted PHP classes, the truth is that developing something that has been already created by someone else happens very often. However, with the introduction of the Standard PHP Library (SPL), hopefully these programming habits will start to change.

Among the numerous and cool features introduced within the SPL package, there’s one that I found especially appealing, because it has become a real time saver in many situations. I’m talking about the set of iterating classes, aimed at traversing different data structures, that is arrays, files, objects and so forth, by using a simple “foreach” language construct.

If you’ve already tasted the power of at least one of these classes, then you know what I mean, because no matter what elements you work with, they can be iterated by the same interface. This is particularly useful when using the “DirectoryIterator” class, which is an important part of the SPL package. Obviously, as its name suggests, this class not only will allow you to traverse any directory by utilizing a regular “foreach” loop, but it will also let you handle information related to the directory in question, by using a few straightforward methods.

Because this class might be handy to use in projects where handling directories is a must, in this new series I’ll be taking a close look at some of its most important methods. We will explore these methods appropriately in conjunction with the corresponding code samples. Therefore, get ready to see the real power of this class. Let’s begin this journey right now!

{mospagebreak title=Why you should use the DirectoryIterator class: examining a concrete example}

Before introducing the goodies of the “DirectoryIterator” class, first let me show you an illustrative example that will demonstrate why this class should be used,  particularly in those cases where you need to work intensively with directories inside an application.

All right, say you need to read the contents of a given directory and process these results. This sounds like a typical situation that can happen during the development of a Web application. So, considering this case, I’d be able to code the following class, which reads the contents of a particular directory:

class DirectoryProcessor{
    private $dirPath;
    public function __construct($dirPath){
        if(!is_dir($dirPath)){
            throw new Exception(‘Invalid directory path!’);
        }
        $this->dirPath=$dirPath;
    }
    public function fetchContent(){
        $output=”;
        $dp=opendir($this->dirPath);
        while($file=readdir($dp)){
            $output.=$file.'<br />';
        }
        fclose($dp);
        return $output;
    }
}

As you can see, the class shown above, called “DirectoryProcesor,” is capable of taking up a specific directory path and reading its contents by using its “fetchContent()” method. The class is indeed basic, but it does what I want. An example of its proper utilization can be seen below. Please take a look:

// example for using the “DirectoryProcessor” class
try{
    $dirProc=new DirectoryProcessor(‘default_path/’);
   
echo $dirProc->fetchContent();
}
catch(Exception $e){
    echo $e->getMessage();
    exit();
}

The above script shows how to use the class defined previously to read the contents of a hypothetical directory. Now, suppose that you have a sample “default_path” directory, which also contains two text files, called “file1.txt” and “file2.txt” respectively. Based on this condition, the above script would output the following results:

.
..
file1.txt
file2.txt

As you can see, my “DirectoryIterator” class has done a decent job, since it can read the contents of the mentioned “default_path” directory, as you can see from the results listed above. However, although this class is capable of doing a good job with regard to handling directory contents, the truth is that this process can be performed without the need to code a custom class.

What’s more, data contained in directories can be handled in different ways, which is very convenient when coding an application that will perform these kinds of tasks. But how can all these things be achieved? The “DirectoryIterator” class that comes with the SPL package can fit the most common requirements for traversing directories, therefore in the following section I’ll show you how to use this class, and explore some of its most relevant methods.

To learn more on how this class works, please click on the link that appears below and keep reading.

{mospagebreak title=A standard way to traverse directories: using the DirectoryIterator class}

As I said right at the beginning of this article, the “DirectoryIterator” class bundled with the SPL package allows you to traverse any directory by using  a typical “foreach” loop. Now, keeping in mind the example that you saw in the prior section, have a look at the following one, which shows why the “DirectoryIterator” class can be a real time saver:

// traverse directory with ‘DirectoryIterator’ class
$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
   
echo $dirContent.'<br />';
}

Did you think that traversing directories with this class was much harder? Not at all! As you can appreciate, first I created an instance of the class, and passed to its constructor the path of the directory being read. Next, I used a simple “foreach” loop, handy for reading the respective contents.

Obviously, this short code snippet outputs the same results that you saw in the previous section. They’re as follows:

.
..
file1.txt
file2.txt

Wasn’t that great? With a few lines of code you get the same results, and all without having to code a custom class. However, this is only a humble beginning, since the “DirectoryIterator” class features plenty of useful methods, which can be used for processing directories in all sorts of clever ways.

Since you have now realized the capabilities that come with the “DirectoryIterator” class, in the next few lines I’ll provide you with some helpful pointers on how to use some of its most significant methods. Therefore, please read the following section.

{mospagebreak title=A deeper look at the DirectoryIterator class: using the key() and current() methods}

As I mentioned in the previous section, the “DirectoryIterator” class has a bunch of handy methods which are really simple to use. To start seeing the actual functionality of this class, I’m going to show you how to use its “key()” method, which displays the key of each element contained inside a specific directory (remember that the directory on its own is evaluated as an array):

$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    echo ‘Key of current element is as follows :’.$dirContent-
>key().'<br />';
}

In this case, the above script takes up the “default_path” directory and loops over all its elements. As you can see, the respective “key()” method displays the following results:

Key of current element is as follows : 0
Key of current element is as follows : 1
Key of current element is as follows : 2
Key of current element is as follows : 3

Based on the contents of the directory that I used from the very beginning, the above example shows how to return the key of each element inside the specified directory by utilizing the “key()” method. Simple and efficient, isn’t it?

Now, after proving the functionality provided by the “key()” method, let’s move on and have a look at another useful method. In this case, I’m referencing the “current()” method, which can be used as follows:

$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    echo ‘Value of current element is as follows : ‘.$dirContent->current().'<br />';
}

As you can see, the “current()” method is quite straightforward, since it simply returns the current value of the directory element being traversed. With reference to the results returned by the prior example, the output is as follows:

Value of current element is as follows : .
Value of current element is as follows : ..
Value of current element is as follows : file1.txt
Value of current element is as follows : file2.txt

Now, do you see how a specified directory can be traversed as you’d do with regular array elements?

Okay, at this stage, you hopefully learned how a couple of helpful methods that belong to the “DirectoryIterator” class can be used to iterate over each element, as you’d do with ordinary arrays.

However, I’m not finished yet, because there are still more handy methods to review. Over the course of the following section, I’ll show you how to use an additional method which turn the “DirectoryIterator” class into a valuable piece of code.

To see how this brand new method will be used, all you have to do is click on the link below and continue reading.

{mospagebreak title=Resetting a directory’s internal pointer: the rewind() method}

I’m pretty sure that you’ve realized the great functionality provided by the “DirectoryIterator” class. Nevertheless, I’d like you to learn an additional method that can be really useful when working specifically with directories.

Since the code samples that I wrote before showed how easy it is to work with directories that can be handled as array elements, this new example demonstrates how to use the handy “rewind()” method, which wraps the overall functionality exposed by the “DirectoryIterator” class. Take a look at the following source code:

$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    echo ‘Value of current element is as follows : ‘.$dirContent->current().'<br />';
}
// reset directory pointer by ‘rewind()’ method
$dirProc->rewind();
// display first element of directory
echo ‘First element in directory is the following : ‘.$dirProc->current();

As the above example illustrates, the “rewind()” method behaves nearly identical to the “reset()” function that you’ve probably used hundreds of times when processing regular arrays. In this case, after iterating over the specified directory, the script resets the internal pointer, and finally displays the first element of that directory. This condition is clearly reflected by the following output:

Value of current element is as follows : .
Value of current element is as follows : ..
Value of current element is as follows : file1.txt
Value of current element is as follows : file2.txt
First element in directory is the following : .

All right, I guess that this final example gives you a good idea of how the “DirectoryIterator” class can be used to traverse a particular directory. As homework, I suggest you to tweak all the code samples shown here and introduce your own improvements. Fun is guaranteed!

Wrapping up

That’s all for now. In this first article of the series, I covered some of the most relevant methods that come with the “DirectoryIterator” class, in this way demonstrating how easy is to traverse any specified directory with a regular “foreach” loop.

But this story isn’t over yet. In the next article, I’ll be reviewing other cool methods, which can be very convenient for obtaining information such as size, path, and files contained inside a particular directory. I’ll see you in the next part!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan