Using Object Oriented Programming (OOP) in WordPress is fairly common in plug-ins. It’s less common for themes. But I’ve been fascinated with the idea, ever since I heard Kevin Fodness talk about it at a WordCamp in Saratoga a last summer.
A couple weeks ago, I got involved in the WordPress Developers Club. The emphasis of the Club is upping the standard for code within the WordPress community to bring it into line with the best practices across the rest of the coding world. Best practices includes, among other things, object oriented programming.
So I started a new theme project with the idea that it’ll be OOP from the ground up. I’ve put the first few files for the project on Github.
The first step (besides creating the few required files for a WordPress theme) was to write a class autoloader. WordPress doesn’t have one built in.
I found Paul Underwood’s little post about Namespacing and Autoloaders in Plugins helpful in getting me pointed in the right direction on this.
Going by Paul’s suggestion, we can take the theme name as our project’s namespace, and sub-namespace out all the directories within the theme. From there, a fully qualified class name will give us the path from
get_theme_root() to the file that needs to be loaded.
The resulting autoloader looks like this: