One of the advantages of working with object-oriented programming is the ability to define interfaces so classes that implement those interfaces have a strict set of functions that said classes must implement.

WordPress Plugin Interfaces

That is the definition of a class interface, anyway:

An interface is a contract specifying a set of methods, fields and properties which will be available on any implementing object

But how might this look if we’re aiming to create a namespaced solution for including WordPress plugin interfaces (or an interface) for a class that can be used to enqueue stylesheets or JavaScript files?

WordPress Plugin Interfaces: Assets

For the purposes of this post, assume that we’re defining an interface that will be used in the administration area of WordPress. That is, we’ll be creating an interface that will be used to enqueue stylesheets and JavaScript files.

We’ll need to incorporate the following:

  • a namespace that can be used throughout the project,
  • a function for initializing the class,
  • a function for actually enqueuing the assets.

And since this is generic enough that it can be used for JavaScript and stylesheets, I’ve opted to simply call it Asset.

The end result may look something like this:

View the code on Gist.

Next, we need to actually implement the interface with a class. It should be relatively straightforward since we’ve set the methods that must be implemented.

Notice, however, that I provide a couple of properties that are set in the constructor of the class. These are specific to this class and make the act of actually enqueuing a file a bit easier.

View the code on Gist.

A few things to note about the code above:

  • it uses the use keyword so that PHP knows we’ll be working with the Asset interface,
  • I’ve prefixed the name with JavaScript so it’s clear what type of asset I’m working with.

Finally, to instantiate the class that implements the interface, you simply do this:

View the code on Gist.

Sure, this particular example is simple and I’ve left the usual code comments out but that’s generally for the sake of readability. If you want to see something like this in action, then review the source code for

If you want to see something like this in action, then review the source code for this particular plugin.

Share:

Leave a Reply