Bringing OOP functionality into WordPress

So if, like me, you’re an object orientated programmer and are suddenly asked to build functionality into WordPress it can feel like you’re trapped into procedural code and functions. Consequently; I thought I would whip up a little tutorial of how to work within WordPress, whilst maintaining your OOP integrity. The reason this is important is quite simple, if you’re building complex functionality into WordPress, you want to be able to use OOP principles and methodologies.

Don’t worry or get confused, themes vs plugins

Essentially, these are the same thing! They use the same library of code, the APIs you can use within WordPress are the same. You could be asked to implement the code in either, and you’ll do it the same way. The real difference is whether you want the functionality to be exposed if the website changes theme, if that’s the case you’ll move the code into a WordPress.

PSR-4 Autoloading

The first thing you’ll want to do is get some PSR-4 autoloading running so that you can use your classes without having a huge set of require, require_once or include statements which can be a nightmare to maintain. If you’re working in a theme put this code into your functions.php – if you’re in a plugin then I would advise you do this in the registration file which might be wp-contents/plugins/yourplugin.php or it might be wp-contents/plugins/yourplugin/functions.php. If in doubt, look for the declaration of the plugin – which will be a PHP code comment as seen here.

I will use JohnoTheCoder as my vendor name and PluginTutorial as the project namespace. The file we’re putting this code into is called whenever WordPress is loaded (because the theme is initialised, as are the plugins) – so you’ll want something like this

/*
    Declare the autoloading - you can repeat this for all your different namespaces if you wish, for example if you're bringing in code from other repositories
*/
spl_autoload_register(function ($class) {

    // The classes I want to autoload are within the JohnoTheCoder\PluginTutorial namespace
    $prefix = 'JohnoTheCoder\\PluginTutorial\\';

    // The class being loaded is not within my namesapce, return early
    if (strncmp($prefix, $class, strlen($prefix)) !== 0) {
        return;
    }

    // All we're doing here is saying that your namespace classes are found within the src subdirectory
    $file = __DIR__ . '/src/' . str_replace('\\', '/', str_replace($prefix, "", $class) . '.php';

    // If the file does not exist - throw an exception with a helpful message
    if (!file_exists($file)) {
        Throw new Exception("Class [$class] not found in expected location [$file]");
    }

    // The file does exist, so require the file
    require_once($file);

});

What this means now is that you can reference JohnoTheCoder\PluginTutorial classes, and they will be looked for within your plugin, for example JohnoTheCoder\PluginTutorial\Subspace\MyClass would be found in plugin-directory/src/Subspace/MyClass.php – of course you can modify this to follow the naming conventions you have in place.

That’s it for this short tutorial – I’ll do some more “OOP in WP” tutorials in the future, to enhance maintainability and help encourage true OOP development within WordPress plugins and themes.

Tips for commercial WordPress, and open source, development

Hi everyone

So I’ve been using content management systems on and off for the best part of 10 years. From the by-gone days of PHP Nuke and when content management systems like PHP Fusion were all the rage. To using more modern, and definitely more widely adopted systems like Joomla and, of course, WordPress; and just to throw other open source stuff into the mix, platforms like Moodle.

Now I’ve returned to using WordPress on a daily basis, but from a different perspective; I don’t do too much development on WordPress personally; my skill set generally lies in building things on frameworks such as CodeIgniter and Laravel, if not bespoke. But I do use WordPress to the extent of managing multisite installations, managing production stability and servers, as well as deployments and migrations.

Having been in the unique position to pick up some legacy code in my time, and seen what does and does not make a WordPress site easy to work on, manage and maintain; I thought I would put together some tips for building WordPress sites, and functionality, which will stand the test of time.

1. Never modify the core

This is a deadly serious one. No matter what you’re working on it should have a specific way of extending functionality, whether through plugins and themes, extensions or a specific namespace where modifications should be added, never, ever, ever modify the core. The same applies to the core code on a plugin.

The reasons for this are really simple; you probably don’t know and understand the full architecture or what you might break by changing this, and more importantly the biggest strength of using something open source is that updates are generally frequently available. The moment you change something in the core you’re going to sabotage any upgrades; you will have to make the choice. Either update the software (absolutely critical) and lose your changes, or don’t update the software and risk leaving bugs, security vulnerabilities, and all kinds of other stuff in there. Not a good position to be in.

2. Choose the right one

WordPress is the most widely adopted content management system in the world. Impressive, right? And technically, yes, anything can be built on it. In the same way any system can be built using .txt files for data storage. It can be done, but that doesn’t mean it should be.

I’ve laboured this point a few times in a few articles and things, but a good developer will know the tools available to them and choose the best one for the job. It is worth spending six months for a content management system and blogging platform, that does exactly the same as WordPress? Of course not. Is it a good idea to build a secure intranet containing sensitive data about national security on WordPress? Of course not. It’s about knowing what’s available and making the best decision based on this.

This is a difficult one, however, as you need to choose the one that fits your needs right now, as well as being compatible with the long term visions of the site; or know from the start that a rebuild will be necessary.

3. Be wary of plugin dependencies

Why use plugin_function when cms_function does the same job, and is probably going to be better supported in the future? When installing plugins, extensions and add ons; always think about the eventualities? What if this plugin’s core is compromised and I need to disable it right now; what will break? What if the plugin stops being supported? How tied into using it am I right now? If you’re managing lots of websites, especially; be wary of the headache you’re going to have if you’re relying too heavily on too many plugins.

If you notice yourself using plugin X on every site you build, or relying on it super heavily, it might be worth doing one of a few things. Either building your own replacement, so you’re in control of the core. Or perhaps wrapping it in your own functionality, so if you want to swap it out, you can. Using a technique called Facading can help with this, hiding plugin functionality behind you facade means you can swap what’s behind the facade out if you need to.

Really the point here is don’t install things willy nilly, think about the dependency you’re creating on this plugin for your website, and how much of a pain it’s going to be if you want to remove it.

4. Always check the source

Depending on the project and the size reading the source code line for line probably isn’t going to be efficient; so that’s not what I’m suggesting here. By source I mean the author, the factory, the company; wherever it comes from. Make sure they’re trusted, WordPress, for example, examines all of the plugins and themes submitted to their public repositories and they’re pretty stringent on their standards, as well as ensuring they’re safe (from a security standpoint).

Most mainstream CMS have white hat security scanning tools that will uncover most, if not all, known security flaws and vulnerabilities. Running these can only be a good thing, as long as you act on the results you get.

5. Don’t be afraid to code things from scratch

There might not be a plugin which does what you want, or doesn’t do exactly what you want. You have 10 requirements from your client. Plugin X fulfils 9 of them. Do not try and hack it to fulfil the 10th, it will only go badly; honestly, I’ve been there and done it a bunch of times.

Just because you usually use X plugin and Y CMS, doesn’t mean you have to this time. Some things are best built from scratch, whether the whole site/software, or a specific functionality. Sometimes the best option is to get stuck in with coding the thing you want. You’d be surprised at how quick this can sometimes be. And just because your CMS offers a specific functionality doesn’t mean you have to use it. WordPress Custom Post Types are a beautiful example of this, as well as their taxonomies. These are both beautiful pieces of functionality; but they’re not the best way to store bespoke data, for example. They exist for a range of things, but primarily to give you a way to show bespoke content, like recipes, and linking them together in a specific way, dietary requirement for example. Storing anything that doesn’t fit into a custom post type and taxonomy doesn’t make sense, so don’t do it.