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.

PHP Interfaces, Traits, and Inheritance, how and when to use them

Hi all

So this one is going to be fairly short and simple, I hope! What I am going to cover, and this does assume so prior knowledge, is what interfaces, traits, and inheritance are; and some different use cases for them.

So the first one, and maybe the easiest one to cover, first:

Inheritance

In its simplest term, and I’m going to try and keep things simple in this article. In very brief terms, inheritance is about extending something which exists. Of course, you may well have created this base on which you’re extending.

Simple use case: User class, extended by an Administrator class. This would be because that an Administrator can do everything a user can do, but a User can’t necessarily do everything an Administrator can do.

The way you would do this in PHP would look like:

class User
{
    // Regardless of whether you're a standard user or an administrator you would have access to this method
    public function getUserId() : int
    {
        return $this->id;
    }
}

class Administrator extends User
{
    // Only administrators can delete users
    public function deleteUser(int $userId)
    {
        // Do something here
    }
}

Of course, there are a million ways of using this, but essentially what you’re doing here is following a single line of inheritance, each extension gaining its own functionality. Something else of note is that you can override (except where the final keyword is used) methods and classes.

There are many ways you might want to do this, including several layers of inheritance, or multiple classes extending the same base.

Interfaces

This is concept defines a set of interfaces (or integration points), though the key theme here is that an interface can be applied to anything. You’re specifying very little, except that the class implementing this interface must abide by the rules laid out.

interface Notifiable
{
    public function getEmailAddress() : string;
}

Now the thing to note here is that the interface simply doesn’t care how you retrieve that email address, but you must have a way of doing it, and any class this is applied to must follow those rules.

The easiest use case for an interface, that I can think of, is something like the above. Notifiable, anything within your system could be notifiable. An instance of the system, a user, an organisation, a team or department. It doesn’t matter, applying the interface means that it could be parsed and handled, through a notification service.

Traits

I’ve tried to explain this one recently, and the use case for it. The easiest way I found of explaining it recently has been: An interface lets you define the input and output of some methods, inheritance lets you gain functionality from parent classes. Traits are for where you don’t want to use parent classes (because you can only extend one class at a time), but want to bring the “meat” of some methods across.

At the risk of causing some controversy here (again) I’m going to say the easiest use case to explain with traits is a logging class, which might look something like

trait Logger
{
    // PSR-3 compliant functionality here
}

class MyThingDoer
{
    Use Logger;
}

All this does is allows the MyThingDoer class to do anything that the Logger trait specified.

In Summary

I’m not necessarily advocating the use of these three sets of functionality, or how they should be used, or anything like that. I’m simply documenting their existence and usage in a way that those moving from PHP procedurally into a structured OOP environment might understand it.

I understand there are dependency injection arguments regarding traits, and I think that is a conversation for another day.

So, in a sentence. When you want to have a base class, and things which logically make sense to be extensions – use inheritance. When you want to ensure conformity to a set of rules, so that objects can be parsed into service providers, use interfaces. When you want to simply share functionality across multiple classes, use traits.

I hope this has helped, of course, if you have anything to add, anything you’d like to say or anything to contribute, stories, personal experiences, etc. as always feel free to drop it in the comments.

Quick Life Hacks with the Eloquent Model

Hi folks,

It’s no secret that I love Laravel, and especially love Eloquent. This post isn’t about why various people don’t like Eloquent, etc, etc. but just some “life hacks” of working with Eloquent.

#1 – Naming Conventions

I personally like to use the following naming convention on my databases (using a forum as an example)

forums
forums_topics
forums_topics_replies

Whereas Eloquent would expect the following:

forums
forum_topics
forum_topic_replies

I personally dislike this, for no other reason than I like to be able to see what’s being owned by what at a very quick glance. Additionally, namespacing; I like to namespace my Models, at the very least into a Model namespace, but often I like to further namespace these to represent the ownership of the data; so I end up with something like (I’m using a directory structure, because PSR-4 namespaces follow this anyway)

app/
- Model/
- - Forum
- - ForumTopic
- - ForumTopicReply

My only issue with this is that the Model namespace can end up huge, and with classes with some really ridiculously long names. So I prefer to break this down like so:

app/
- Model/
- - Forum
- - Forum/
- - - Topic
- - - Topic/
- - - - Reply

I realise this begins to look like overkill, but I find it particularly useful when separating functionality by module or something like that.

The Autonaming

The above means I have two options, number one is to follow the convention to the letter. Option two is to overwrite the naming convention on a base model, from which I then extend. This base/abstract model contains the following method:

/**
 * Overwrite the autonaming conventions
 * @return string
 */
public function getTable()
{
    $class = substr(get_class($this), strlen(self::MODEL_NAMESPACE));
    $namespaces = explode('\\', $class);
    foreach($namespaces as &$namespace){
        if(substr($namespace, -1) == 'y'){
            $namespace = strtolower(substr($namespace, 0, -1) . 'ies');
        } else {
            $namespace = strtolower($namespace . 's');
        }
    }
    return implode('_', $namespaces);
}

Note: You will need to have the MODEL_NAMESPACE constant declared as well

All this does is turned app\Model\Forum\Topic into forums_topics, but it’s pretty useful

PSR-2 properties

So the other thing I find occasionally annoying is that when writing PHP my properties follow the PSR-2 naming convention (camelCaseForVariables) – but using eloquent I am forced to snake_case_columns because (understandably) this is what is in the database.

By adding the following 3 methods to your base model you can use PSR-2 compliant field names. So that created_at becomes createdAt; without having to modify the database;

/**
 * Overwrite the getter so that we can use camelCase field names
 * @param string $property
 * @return mixed
 */
public function __get($property)
{
    return parent::__get($this->convertToSnakeCase($property));
}

/**
 * Overwrite the setter so that we can use camelCase field names
 * @param string $property
 * @param mixed $value
 */
public function __set($property, $value)
{
    parent::__set($this->convertToSnakeCase($property), $value);
}
/**
 * Turn a camelCase string into snake_case
 * @param $string
 * @return mixed
 */
protected function convertToSnakeCase($string)
{
    return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $string));
}

Quite simply, all these methods are doing is plugging into the original getter and setter, but first converting camelCase to snake_case – so that throughout my code I can refer to these fields in a way which is fitting with the rest of my code, which conforms to PSR-2

There you have it

A couple of very quick, but very useful, ways to extend the base Eloquent Model so that it is in better fitting with the rest of your code base and database standards (or mine, anyway)

Quick and Easy PHP Singleton

Hi guys

A really short one today, just because someone asked me about it a couple of days ago. I also though it potentially best to avoid something as controversial as my last post about Eloquent and the Single Responsibility Principle, which caused a bit of a stir during the week.

So, you want to make sure you only ever use one specific instance of a class (maybe a DB connection) and need a quick and easy way to do it. Personally, this is the technique I would use:

<?php

class MySingleton{
  
  // This will hold the instance of the class
  private static $instance = null;
  
  // Declare this as private to stop anybody being able to use the "new" keyword
  private function __construct()
  {
    // Your usual constructor stuff in here
  }

  // This is where you get your instance
  public static function getInstance()
  {
    if(is_null(self::$instance)){
      self::$instance = new self();
    } 
    return self::$instance;
  }

}

All we’re doing here really, in a set of steps:

  • You need a way to hold an instance of the object which is persistent throughout the execution
    This is what the private static $instance is doing
  • You don’t want anybody to be able to directly use the new keyword, because then you’ve lost control of the instances of the object
  • You need to be able to get an instance of the class, which is what the getInstance method is for
  • In getInstance all we’re doing is instantiating the object if one hasn’t get been stored against the $instance static

So, to fetch your instance is simply:

$singleton = MySingleton::getInstance();

Wherever you run that throughout your code you will receive the exact same instance. Particularly useful in things like Database connections, loggers/debuggers and things like that.

Some quick translations, OO PHP to C#

So a recent project has facilitated me brushing up on my C# – so I thought I would share some basic translations of things that can be frustrating when you know the usual programming principles (object orientated programming), but not all the syntax.

A quick couple of points to note:

  1. C# is a strictly typed language, that means you have to know about what your variables are going to be, and yes, you have to declare them somewhere sensible
  2. Accessing methods and properties within your class does not require usage of $this – you’re talking about true scope of variables and methods, so you don’t have to worry about it
  3. Public, protected and private are essentially the same
  4. You have to declare the return types on every method, none of this return an object or false stuff
  5. Namespacing is essentially the same as if you were following the PSR-4 standard
  6. Everything, including strings, are objects
  7. A single quote and a double quote are fundamentally different things

Declaring a variable

Okay, so starting with the basics, declaring a variable is basically the same, except you have to declare the type, so declaring age as a variable, integer, with the value of 25 would look like this in PHP:

$age = 25;

However, in C# it would look like this

int age = 25;

Moving into this being a property in a class, you must rather than optionally, or have to if you’re conforming to PSR-2, so in PHP it looks like this

public $age = 25;

In C# it’s going to look like this:

public int age = 25;

Declaring methods

Okay this is an easy one in PHP, it looks something like this. Using PHP 7.1 we can strictly type the return.

public function myMethod(MyClassOne &$argumentByReference, MyClassTwo $argumentByValue) : ObjectClass

{

    // Do something in your method here

}

// This would be called by doing something like
$object->myMethod($parsedByReference, $parsedByValue);

This one gets slightly different when translated into C# for a couple of reasons. You must declare the types of the parameter, the type of the response(s), it also gets a bit different when calling the method too:

public ObjectClass myMethod(ref MyClassOne argumentByReference, MyClassTwo argumentByValue)

{

    // Do something in your method here

}

// Now calling your method would look slightly different

Object.myMethod(ref parsedByReference, parsedByValue);

Using Objects

Instantiating objects isn’t much different either, really; it looks different but that’s because it’s strictly typed.

Main difference between use statements in PHP and C# (other than that it is using in C#) is that you use a namespace, the classes contained therein (this namespace only, not its children) are automatically available.

In PHP I want to include a class and then instantiate it, will look something like this:

use Vendor\Project\Namespace\ClassName;

// Then you have all of your usual declarations, which we'll get to

$myObject = new ClassName();

However when you want to do this in C# it looks something like this:

using Vendor\Project\Namespace;

// Then all of your usual declarations

ClassName myObject = new ClassName();

Declaring Classes, using Inheritance and Interfaces

This gets a bit different, but only syntactically. We’re going to create Person as an abstract class, this will be extended by the Employee class. Employee is going to implement an interface called Emailable.

For the sake of ease I’ve not separated these into different files

In PHP it would look like this:

abstract class Person{

    // Shared functionality here

}
interface Emailable{

    // Interface requirements here

}

class Employee extends Person implements Emailable{

    // Employee functionality, including Emailable requirements, in here

}

In C# however it would look like this

namespace ObjectOrientatedPrinciples.MyExample
 {
    abstract public class Person
    {
        
    }
    interface Emailable
    {
        
    }
    public class Employee : Person, Emailable
    {
        
    }
 }

You will see from this that C# doesn’t necessarily draw the distinction between classes being extended and interfaces being implemented.

Arrays and Lists

This is actually the only thing I found to be a little bit painful, however there is a decent tutorial on arrays on the Microsoft Developer Network (MSDN)

Closing Off

I’ll leave it at that for tonight. But a quick few bits that I thought might help someone out, it would’ve helped me if I could’ve found this article this morning. Though admittedly probably only saved me an hour or so. Not the point though, here it is 🙂