Ordered Results using DirectoryIterator

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)

Benefits to Proxying APIs Using with Your Own Servers

Last night I was hacking away at some new features in EraseUrX and I ran into, what I still don't know is, a coding error on my part or incomplete api with Facebook. At this point it really could be either one. I am using their graph api and have no problem authorizing a user, requesting extended permissions and getting a list of friends from that user.  However, when I try to post a message to someone else's wall I get an OAuthException message that Facebook couldn't authorize the application.  WTF?! I thought possibly that my access token was invalid or that my url that I was posting with was incorrect. Nope they are fine. I tested it using curl and the post went through just fine with the same access token. After a few more code changes to no avail I decided to approach it from a different angle.

Though most big services take a lot of pride and care in their API's that they produce they still inevitably change method names, authentication schemes, parameters, validation, etc. This type of uncertainty isn't easily managed when you have compiled code on a device.  If/when a service provide decides to change/delete something from their API, your app could possibly break leaving the users pissed and blaming you.  Even though it TECHNICALLY isn't your fault, developers should take ownership and responsibility to do whatever they can to provide applications with the best user experience.

I decided that I would create a small webapp/script on my server that would act as a proxy or broker between api calls from my app and Facebook. On the surface it looks like it is overkill, but the benefits definitely outweigh the overhead.

A standardized output
Depending on if my request is successful or not to Facebook I will get a different JSON response which is fine, but the JSON structure is also different.  If I were do to all response checking on the phone, not only is it EXTREMELY verbose, but I don't want to have to parse through two different object graphs.  Instead my webapp will get the respone(s) and create a standard response structure of my choice. Something like this:

// Success
{
  'status': 'success',
  "data": [
      {
         "name": "John Doe",
         "id": "55555"
      },
{
         "name": "Jane Doe",
         "id": "6666666"
      }
  ]
}

//Error
{
  'status': 'error',
  "data": [
      {
         "message": "Bad error message",
   "title" : "Bad error message  title",
         "type": "666"
      }
  ]
}

Having a standardized response my app code looks for an exact value in the json string, 'status', and transverse the rest of the json response and process everything accordingly.  Efficiency.

APIs Change
As stated above service providers (Facebook, Twitter, Google, etc.) can/will change their api at any given time.  It is by far easier to change code in a webapp, test and deploy then it is to modify code, no matter how well written it is, in a native device app.

Better Monitoring and Logging
Having your native apps hit your script will allow for better monitoring of a) how many user's are actually using your app b) if there are errors you can track down them down easier and faster c) more accurate analytics that are based on your use cases.  In addition, being able to integrate those stats into other business initatives and integration points.

Result Caching
I would bet that companies like Facebook are caching result sets for a better/faster response, but we will never know and to the full extent they are caching.  You can setup your own caching architecture that will best serve you and your apps needs supplementary to whatever may or may not be provided by the service.

Disaster Recovery
We have all seen the Twitter "fail whale" which means that ANY app trying to utilize that API is housed for x amount of time, which is not a good thing.  Having your own server side script would allow you to handle those unfortunate instances when the service is unavailable by using a cached copy of the result set if one is available or send back a message in your standard response that allows your app to present to the user that that piece of functionality isn't working at the moment.

By handling the majority of the requests/response on my server I reduce the amount of boilerplate code/frameworks that are in my iPhone/Android/Blackberry app, able to standarize the message format for more efficient parsing on the device and provide a better user experience.