Over the last few posts, I’ve walked through the process of taking an idea from concept to prototype.

Granted, there are some things that you might change (and there are some things I’d change regarding organizing classes). But the point of the series isn’t to walk through all of the various object-oriented techniques that can be used to create a solution.

Instead, it’s about taking a prototype and converting it into something a little more professional. There’s still one thing that we need to do, though.

Right now, we include all of our files through require statements. And this works alright for small files, but introducing autoloading in conjunction with namespaces can make the application even cleaner.

And that’s what we’re going to do.

Introducing Autoloading

Recall from an earlier post (if you’ve read it), that autoloading is a simple idea:

It sounds great, right? But there’s a caveat: You have to write the autoloader. PHP can’t figure it out on its own.

And this is why I’m a fan of making sure our namespaces also follow a consistent directory structure: If you parse the namespace and the name of the file, it’s relatively easy to build the path to the file and automatically load it.

Sound confusing? First, let’s take a look at where we’ll place the autoloader regarding our directory structure:

Introducing Autoloading: The File

Next, update your plugin’s bootstrap file so that it only requires the autoloader file.

Of course, we need the autoloader to load our files. Essentially, the way it works is this:

  1. separate the components of the incoming file name (like the directory path and the file name),
  2. replace any underscores with hyphens to make sure the file is following the structure of the class’ filename,
  3. start building the fully qualified path name (which is the directory, file name, etc.),
  4. iterate through the namespace down to the class name and build a fully qualified name to the file,
  5. include it in the project.

It’s straight forward, isn’t it? If you follow a consistent namespace, directory, class name, and file naming schema, you can reuse the same autoloader in any projects.

Here’s a copy of an autoloader that I use and drop it into almost any project I use. You’ll see that it follows exactly what’s covered above:

And with this, the plugin is wrapped up to version 1.0.0. You can check it out on GitHub (both literally and just for review). And hopefully, this has helped with walking through the process of going from rapid prototyping to concept within the concept of WordPress.

Series Posts

  1. Rapid Prototyping with WordPress: From Concept To Plugin
  2. Rapid Prototyping with WordPress: Concept Analysis
  3. Rapid Prototyping: Prototype To Code, Part 1
  4. Rapid Prototyping: Prototype To Code, Part 2
  5. Rapid Prototyping: Introducing Autoloading