So I started with a simple idea, what if I was able to take the functionality of X and use it on Y? You’ll find out what “X” and “Y” is later on, but that’s not important. What I actually wanted to write down was my thoughts on writing an autoloader in php. Technically I’ve written an autoloader before, but in coldfusion. This was during a time that I was tasked with rewriting an entire application’s control panel area. I wanted to revisit the idea of an autoloader as a part of a dumb project I was supposed to hack together in two days.

However, I eventually started overengineering the entire thing because I didn’t want to repeat the mess of spaghetti code that is dfo pvp project I talked about in an earlier blog (I still plan on refactoring that later.) I plan on talking more about this project I’m currently working on later.

The autoloader that I wrote for my php project is pretty simple, here’s the raw code. I’ll give a description for what’s going on after the break:


This autoloader was written to loop through four sets of directories (at least for me, this autoloader can be repurposed for pretty much anything.) Those directories are: application, controller, model and view. I wanted to loop through all the directories and subdirectories in a recursive manner. Once I find a file that’s not in the $ignoreList array I add that path to the namespace’s fileNamePath collection. Then I take those paths and find the filename itself by exploding the array by the “\” character. I look for the very last entry in that newly formed array in order to obtain the filename.

Once I find the name, I then remove the .php filename extension. I do this because I do not need this portion if I want to use it as a namespace. Each of these files names as double as namespaces, hence the name of a lot of the functions in this file. I take the filenames and store them into the array as a potential namespace. Within the file itself, all the function are contained with a namespace with the same name as the file.

Right now, what I envision this autoloader doing is being invoked via include, then auto including all the other files needed. Then I can call the functions I want via a namespace. I will see how this scheme will work out as I build this really stupid idea into fruition. Thanks for coming to my TED talk.

Leave a Reply

Your email address will not be published. Required fields are marked *