No matter if you are beginner or expert one of the most command tasks that you will do is writing some class/script/snippet of directory iteration.
"Get a list of files/directories and display"
With PHP there are about baker's dozen different ways of accomplishing this. In the beginning there was functional verbose way:
It gets the job done, but not very extensive and it seems VERY verbose. Being that my development background started with OOP I was never a fan. Fastforward a little bit and PHP introduced "dir", which returns an instance of the Directory class.
Not to bad, but still verbose and God forbid that you have to do recursion.
With PHP5 came the SPL. Standard PHP Library, which still to this day I don't know why it isn't prompted more. Pure object-oriented and has the flexibility to accomplish the basic tasks set before them, as well as, the strength to be a customizable as the developer wants.
The class which most use for directory iteration is…hold your breathe: DirectoryIterator. In my use case I need to server up image path and meta information in an HTTP request so that an iPhone app could parse the response and grab the appropriate images for display.
Basic usage:
See how easy that was. OOP at it's best except for one little thing. The images were not coming back in the correct order. They are named on the filesystem: "00.png", "01.png", "02.png", etc., but the return was random. While I can appreciate DirectoryIterator being a more "abstract" enumator and not really having a "natural" sort order I still was frustrated. Remember, what I said earlier though about the SPL being customizable and OO. You can subclass the DirectoryIterator and supply your own comparator, which by design, is best practice for a large system. I, however, was looking for the shortest line between two points and creating a subclass seemed overkill.
*I really wish PHP had categories like Objective-C or method swizzling
Not a problem though. I can just pass a callback function to the usort function and call it a day. H.O.P. This logic does work, but the array that I wanted to sort is associative so the key that should be sorted is "name". The callback function for usort ONLY accepts two arguments which it compares. I had to bake in the key which isn't flexible. I would rather reuse the functionality by being able to pass in the key to sort on. PHP isn't the only language that has this result. If you look at the behavior of an NS(Mutable)Dictionary in objective-c which makes copies of keys, so the objects in the key array will be different. Objective-C offers the ability to pass in a comparator when iterating over the dictionary so that the sort order is defined by the developer not by the hash.
In a perfect world I would be able to do the following:
Here is the example script for my use case. (changed some path names for security reasons)