Software, Development, and WordPress

Namespaces and Autoloading in WordPress

In my talk for this year’s WordCamp Atlanta, I’m going to be talking about namespaces and autoloading in WordPress.

Namespaces and Autoloading in WordPress

When I don’t yet have the images I want for my presentation, I use stock photos.

While working on my presentation:

  • I’ve been working on a project for someone in which I’m writing an autoloader from scratch,
  • I’m talking with other developers about their preferences with writing autoloaders,
  • I’m looking at open-source projects to see how others are writing autoloaders.

All of this is primarily done to see how, if it isn’t obvious, others implement namespaces and autoloading in their projects. What’s interesting is that there seem to be three main ways in which people go about doing it.

Namespaces and Autoloading

Before going into the way I currently approach writing an autoloader, I thought I’d share the three ways I’ve found others implementing their autoloaders.

What I’ve Found

And note that this is primarily meant just to be interesting, not to offer any commentary on what way is correct or which way is not.

  1. Writing an autoloader using procedural code even if the rest of the code base is object-oriented,
  2. Writing an autoloader using object-oriented code regardless of which paradigm is used for the rest of the codebase,
  3. Using a dependency manager, like Composer, to load all of the dependencies and forgoing PHP’s facilities for autoloading altogether.

For what it’s worth, I think there’s something to using Composer as an autoloader, but it requires a little more experience with additional tooling than just PHP and the manual to use it. That is to say; it may not be for everyone.

What I Do

I know I’ve written about this before, but I’ve also spent time on different projects writing autoloaders in two different ways:

  1. using procedural code,
  2. using object-oriented code.

And as much of a fan as I am of object-oriented programming, I prefer to write my autoloaders using procedural code.

But there’s a caveat to this. It assumes the following:

  • my code is organized in directories that map to their namespaces,
  • I have a standard by which I’m naming my files (regardless of if it’s PSR or WPCS).

With those two pieces in place, I can usually reuse the same autoloader in multiple projects. This is because it’s predicated on the predictability of the organization and standard of the code and because the code is easy to comment (and thus should be easy to follow) thus easy to maintain.

Only as Much as Needed

There’s one other aspect to writing autoloaders that I’ve come across when working on projects for others in which I can’t always use the standards I prefer: I write only as much as I need.

For example, say that you’re going to write an autoloader for a WordPress plugin. The code has its type of directory structure and file-naming convention so you can’t just reuse something you’ve already written. Further, the project has classes but no interfaces or abstract classes.

And remember: You’re writing the autoloader from scratch.

When doing this, I think some of us have a propensity to want to write an autoloader that supports all of the above but also has support in case an interface or abstract class is ever introduced.

I used to be that way (and maybe I’m the only one that’s every been that way ).

But now I tend to write just enough to make sure it works. That means I will write an autoloader for the above requirements so that it satisfies the use case, but I won’t write code for something, like interfaces or abstract classes, that may never be used.

I can always come back and add that later.

Sharing All of This

For those who are interested, I’ve also been convinced by a friend to publish a post that walks through all of the content in my presentation.

I’m already planning to have a repository on GitHub with examples that I’ll be using during my talk as well as the slide deck that I’ll be using so this is one more thing that I’ll aim to publish when I give my talk.

Namespaces and Autoloading in WordPress

My presentations always start on paper.

And for those who are interested, I’m sharing a couple of shots on Instagram each day as I slowly work my way through putting together the presentation (and as I continue to look for different types of things to share on the social network ).


  1. Seth Carstens

    Hey Tom, I typically follow / read most of your posts for the last few years. I doubt you know me, but I’m pretty well known in my local community. I spent a few months on and off putting together what I call the “abstract plugin base”. I manage a group of developers and we started using it in or projects. Its still in a testing phase, and I’m tweaking it very slightly as needed, but it has an autolloader built into it so that you no longer have to deal with “file includes” as long as you are building your plugin with PSR or file/folder best practices WordPress expects of you. I’d love you to consider it and or give me feedback if you have any.

    • Tom

      Hey Tom, I typically follow / read most of your posts for the last few years. I doubt you know me, but I’m pretty well known in my local community.

      Thank you for reading — and I know you through our exchanges online via comments and Twitter :).

      I spent a few months on and off putting together what I call the “abstract plugin base”.

      Such a solid idea.

      but it has an autolloader built into it so that you no longer have to deal with “file includes” as long as you are building your plugin with PSR or file/folder best practices WordPress expects of you.


      I’d love you to consider it and or give me feedback if you have any.

      If I have the time, I’ll definitely check it out (I’ll bookmark it, for sure). I can’t make any promises beyond that but this is a good thing to be working on, in my opinion.

  2. Rick

    Awesome Tom,

    Can’t wait to see it. I wrote a dependency manager which can defer loading or autoload not long back.

    Much of what you stated I found as well. The dependencies come from a Json file or string and each entry maps to a directory and namespace (optionally used). Additionally it supports a few leading characters that perform tasks.

    For example, “Common/Collections_collection-class.php” , obvious.

    Placing a “#” as a leading character flattens the base directory thus instead of it being in the plugin directory the path lay in the root plugin or root theme directory.

    An @ leading character will remove the WP map path, aka: admin, front, frontadmin.

    Lastly a leading ‘!’ character forces mapping towards redirection of the base directories. This WP directories for example get mapped against an array of directories etc.

    The class takes care of CSS / Javascript enqueue’s as well.

    My goal was simple. The plugin initializes early. In fact, the only code that lay before its instancing is an exception/logging (optional) class and my SDK class that is used for managing editions (aka: Lite, Standard, Pro etc).

    Instancing provides a base_dir (plugin or theme parent), a manifest path to JSON files and an INITial dependency file that in for example, loads up any common’s such as the collections class, used in both backend or frontend. The Initial dependency also does setup of the class, for example, any directory redirection needed. For example, perhaps I wish MAP the admin dir to WP-Admin etc.

    The class is then called from a command processor that examines the URL Params (_GET’s), validates those against an allowable command set array and will automatically load the JSON manifest file for said command/action and optionally autoload it or not.

    Why optionally?

    I made it optional due to the possibility of late dependencies. For example. I coded some JS that allows the user to do customizations of frontend outputs. Since there are differing editions of the plugin I dont want be instantiating some classes loaded via the manifest file until all assets they rely upon on ready. Thus, dependencies can be added late, then the autoload called.

    I do not use PHP’s SPL. It just made no sense.

    I also wanted something that I can re-use and be lean. While its not completely finished and I need refactor a few functions it clocks in under 300 lines of code total.

    Its external lib management is very minimal presently. For many projects I think composer being used for managing a plugin or theme dependencies is just way overkill and frankly can create complexity and performance matters that need not be there while in some ways sacrificing versatility especially when one considers multiple editions of some WP plugin or theme.

    Presently it does not support priority load ordering or class/file versioning.

    One of the neat things about doing this in one’s own codebase is one is not bound to specific parameters for the assets. Since each Json entry whether when decoded maps to array(s) or object(s) it affords agile change for future project considerations.

    For example… Lets just for sake of discussion say that some CSS classes need undergo SASS or LESS before enqueue. A simple addition of a function call to said processor and command added to the files params and good to go.

    As I noted to you previously as a sorta noob to all this, I find that working with WP more unusual than what I am accustomed to. .NET application interfacing is quite different than WP. Thus, I am finding it more condusive to code my own application interfaces to WP than rely on interspersed coupling in my code.

    While to another coder who might reuse or modify my work it creates a level of indirection in what they may be accustomed to the fact that its consistent, reusable, lightweight and extensible I feel completely outweighs what they may face.

    I ran across this with the settings API as well. I needed something agile not only for sake of extensibility but additionally allowing for complex validations and dynamic forms creation. In attempting work with the settings API a great deal of code was interspersed across the plugin settings pages. I tried moving as much as I could into the router which made it a mess.

    Then one day I just said, “To hoot with this fight!” I sat down and coded a forms class. I had to refactor it no less than three times from its initial “Hmmm….” to something now that is as near “Set it and forget it” as I could muster.

    It now happily will consume any jQuery plugins. It has a extremely simple responsive templating mechanism to organize settings, dynamically loads validation classes as needed and totally by accident and 5 lines of code even allows for recursion (inserting forms into the form).

    It is my intent once I document proper and write some explanations to release this stuff for others usage. The forms class (without validators) clocks in at 600 lines of code.

    Currently it consumes arrays… I have debated whether I should change or add to this. Aka: It really does not need to be consuming arrays which get ram expensive (albeit can be unset after processing) when it could consume delimited string / value pairs. Also kickin’ around the idea of using Json which would bring some interesting possibilities. Editing a simple Json file .vs. going into codebase and again perhaps adding extensibility to forms params .vs. needing hardcode some things. For example, JQ asset params into the codebase (arrays consumed) .vs. from a more loosely coupled Json file.

    Ultimately, what I would “like” is for the dependency class and Forms class to work nicely in concert with one another along with my collections class.

    Thus via a standard template for settings and command interface that backend settings development becomes more a “Create your Json” and done. I think it would be a tremendous time saver and be able to create anything from the simple to highly complex settings management and be lean, efficient and extensible in doing so.

Leave a Reply

© 2020 Tom McFarlin

Theme by Anders NorenUp ↑