Tag Archives: wordpress

3 Reasons to use Interfaces in Object Oriented Programming

Although this is primarily a PHP/WordPress blog, this article should be instructive for most programming languages that support Object Oriented Programming. My hope is that it helps you decide to use Interfaces when writing your programming languages. Ultimately, this will help you write better code for yourself and for other developers.

Why use interfaces when writing Object Oriented code?

1. Better documentation

If all of your classes implement interfaces, your interfaces can contain documentation. If you use doc blocks for commenting and automatic documentation, this actually helps to generate comments on classes. Better still, interfaces create a set of instructions that are action-agnostic that allow programs to know exactly what kind of parameters are being requested and, in PHP 7+, exactly what kind of return value is going to be received. Documentation is an incredibly powerful feature that makes interfaces worthy of use all by themselves. But we aren’t done yet… It gets better.

2. Powerful way to conditionally inject dependencies

If you’re using Dependency Injection in your code, then interfaces make your job considerably easier. Because you can implement multiple interfaces on a single object, you can easily add a “UserInterface” with the methods setUser and getUser. In the back-end, you can set up a Factory like so:

class MyFactory
{
    private $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public static function getClass($classname)
    {
        $class = new $classname();

        if (!($class instanceof FactoryMember)) {
            return null;
        }

        if ($class instanceof UserInterface) {
            $class->setUser($this->user);
        }

        return $class;
    }
}

Crucially, this factory does not need to know whether a class has the UserInterface until it creates it. That means that this factory can store any class and auto-magically inject whatever is required.

3. Compatibility checking

If you take a look at the above code, you’ll see an additional interface, FactoryMember. In my example, I wanted to only create classes that implemented a FactoryMember interface. What’s in this interface? That’s up to you. There are cases where such an interface is blank, and you simply want to make sure that a class implements it for compatibility reasons.

In this case, you can think of an interface as also being an attribute of a class. Lets say you have Pet as a base class, with Cat and Dog as child classes. Here are some additional interfaces:

interface Furry {}

interface Playful {}

interface Shy
{
    function run();
}

Of the three interfaces above, only Shy has a method. That’s OK. Ultimately, these are attributes that help to describe pets. Now, you can write a custom message depending on the interfaces that an object has:

$dog = new Dog();

$msg[] = "You see a dog.";

if ($dog instanceof Furry) {
    $msg[] = "There's hair everywhere.";
}

if ($dog instanceof Playful) {
    $msg[] = "The dog's tail is wagging.";
} elseif ($dog instanceof Shy) {
    $msg[] = "The dog is shy and runs away!";
    $dog->run();
}

echo implode(" ", $msg);

Just like that, you’ve used interfaces to help you create a description of a dog. While you could implement each description as a method ($dog->getPlayfulMessage(), $dog->getShyMessage(), etc.), that may not always be desirable. If the messages change based on a situation (maybe when you pass a groomer, for example), then the interfaces can be a very quick way to determine attributes, and a compelling alternative to something like $dog->hasAttribute('hairy') when you’re building an application and don’t know how many methods you might want to call conditionally based on the attribute (aka, run for the Shy interface.

Conclusion

Programming with interfaces is not just a “best practices” convention. Like most best practices, it has a solid payoff for the developer who is willing and able to implement them. It not only allows for better documentation, but it also allows for more flexible use of design patterns and more inter-operable code. Finally, it enables a user to attach custom attributes that can grow with the application. For a little extra work at the beginning, interface programming will reap dividends as your codebase matures.

How and why to write Object Oriented WordPress plugins

Today I want to discuss an object oriented approach to plugin design that works no matter how small or large your plugin is going to become. Once I started doing this, I found it very difficult to return to the old way.

WordPress is… ahem… a “mature” codebase. It’s strength is not necessarily in its modern, lightweight design, but instead in its broad user base and ease of use. These two things are somewhat at odds, given how quickly programming languages evolve.

WordPress is fully compatible with PHP 5.2.9, which means that someone who set up a website 7 years ago at a cut-rate web host, will still get security updates, and, as of now, can still update WordPress to experience the latest and greatest core offerings (although maybe not the latest and greatest plugins) with no issue.

What’s changed between PHP 5.2.9 and now?

  • Introduction of Interfaces
  • Introduction of Namespaces
  • Anonymous functions
  • Anonymous classes

These are just to name a few.

And although PHP 5.2.9 does allow basic but solid object oriented programming techniques, WordPress has a developed enough codebase that a lot of WordPress is built with functions and global variables.

I don’t think you should follow their lead.

To illustrate the difference between the old “WordPress” way, and the new Object-Oriented way (which, in fairness, WordPress implements in many of its newer classes), take a look at these two code samples which do the same thing:


// Procedural
<?php
add_action('init', 'my_long_unique_hello_world_function');
function my_long_unique_hello_world_function() {
    echo "Hello World!";
    die();
}

add_action('admin_init','my_long_unique_admin_hello_world_function');
function my_long_unique_admin_hello_world_function() {
    echo "Hello Admin!";
    die();
}

// OOP
<?php
class My_Unique_Class {
    public function load() {
        add_action('init', array($this, 'init'));
        add_action('admin_init', array($this, 'admin_init'));
    }

    public function init() {
        echo "Hello World!";
        die();
    }

    public function admin_init() {
        echo "Hello Admin!";
        die();
    }
}

global $my_unique_class;
$my_unique_class = new My_Unique_Class();
$my_unique_class->init();

At first glance, the second example is much more verbose, so it’s probably a load worse, right? Granted, for an example with only one action hook, this is overkill. But most plugins do not have just one action hook. Most plugins have several.

And when you get to several action hooks, this becomes really, really helpful.

First of all, rather than having to write a very long function name for your action, you can often write exactly what it is. For example, in my classes, I try to add one function per action per class, so that the init hook always points to the class::init() method. This can make it easier for me to track down coding issues.

Second of all, you may have noticed my little global at the bottom. Because WordPress hasn’t offered a better solution, this is still unavoidable. However, it still dramatically reduces the amount of pollution many plugins would cause in the global scope. Remember, each function outside of a class is also part of the global scope! That increases the likelihood of collisions with other plugins.

Third, this allows you to make full use of object scoping, making things private and protected for internal use only. This may not seem like a big deal, but it can do wonders to remove your dependency on global variables. I’ve used this to build a number of plugins, a good example of which is a footnotes plugin, where each [cite] shortcode is added to a class property and printed as needed (Gist here). Is it strictly necessary to use classes to make something like this work? No. Does it make it a lot easier and dramatically reduce the chance for collisions? Yes!

There’s a lot more to love about Object Oriented programming, including Interfaces, Namespaces, and much more. I’m going to be diverging from the WordPress world to cover some of these concepts, but they should still apply pretty easily. Stay tuned!

Two ways to speed up WordPress

It’s widely held that when you add too many plugins, WordPress gets slow. But what if you need these plugins? Fortunately, you can speed up WordPress on your website, regardless of plugin count.

The fact of the matter is, speed of WordPress sites is almost never a problem with PHP or MySQL, or even Apache. While these can all play their part in slowing a website down, it is generally not the performance killer. The real performance killer? Render-blocking scripts. If you want to speed up WordPress, this is possibly the most important area to tackle.

Check out your Google Page Speed to see what’s happening here. If you’re running a standard WordPress install and have tried plugins that promise faster page speeds with things like concatenation and minification, you’re probably not going to see much difference. That’s because while it will take the browser less time to read these files, and it doesn’t have to read whitespace, it still has to read a lot of the same lines. 50% of a big file, is still a big file.

Think of it this way: It takes you a few milliseconds to load an HTML page – even a PHP rendered one, if it’s well written. Now, imagine loading that same script 20 or 30 times. It will probably take you 20 or 30 times as long. This is especially true on an Apache server because frequently Apache calls these files directly (unless you’re using a caching system – more on that later). JavaScript and CSS files work similarly. Your web page needs to open up these files and process them before being served to the browser. What makes JavaScript a real killer is that the browser needs to parse and execute the JavaScript, loops and all. By default, it does this before the website loads. Additionally, in modern websites, JavaScript operations can be very intensive, so that, taken as a whole, you may have more JavaScript than you do HTML on a given page. This adds a lot of time to your page load.

#1: Asynchronous scripts to the rescue!

It doesn’t take much effort to implement a strategy that can noticeably speed up WordPress. You can do this by making your Javascript asynchronous and/or deferred, which, really simply, means that it can open after your website has loaded. In most cases, the lack of scripts on page load won’t be noticeable, because your scripts will load within a few seconds. What will be noticeable is that your website is suddenly much faster.

There are a few good asynchronous/defer script plugins out there. The two that I’ve used are:

  • Async Javascript – This is a very simple plugin that does what it says it does. It does not defer jQuery by default… Which is good, because that tends to trigger all sorts of errors. You can also exclude files simply by adding the script name, and select between defer and async. I tend to go with async unless I’m getting too many errors, because it guarantees the best page speed. Unfortunately, when a lot of dependencies are required, sometimes it is not feasible. This is also important for any plugins that interfere. In my opinion, this is the easiest plugin to get set up and working the way you want it to work.
  • Fast Velocity Minify – Another great option for plugin developers, this also caches, minifies, and concatenates your files if you so desire. The concatenation is a bit overkill here, but the fact that it has minification makes it a good option to take care of another common Google Page speed gripe.

Important: Make sure you test this out first on a local or staging server.  If you don’t have one, please be aware that this is highly likely to need some fine-tuning, so test your web pages immediately. To see what’s going wrong, in Chrome or Firefox, right click on the page and select Inspector. Then, navigate to the Console tab. You’ll need to track down the specific JavaScript errors. For example, when I received an error for our plugin, Featured Image Pro, that “imagesLoaded” and “masonry” could not be found, I had to create an exception for these two files, which exist in /wp-includes/js/. If this doesn’t make sense to you, STOP and get a developer to help you.

#2 Leverage Browser Caching

Another great way to speed up WordPress is to utilize browser caching. This is something I’m frequently guilty of skipping, but can help you speed up WordPress on your site, because your server isn’t hit when your browser notices that a file it needs is already stored locally. If you have control over your server and you have more than one website, you can do this universally or in your Virtual Host configuration.

Otherwise, put it in your .htaccess file.


<IfModule expires.c>
    ExpiresActive on
    ExpiresByType text/css "access plus 1 year"
    ExpiresByType image/vnd.microsoft.icon "access plus 1 year"
    ExpiresByType image/x-icon "access plus 1 year"
    ExpiresByType application/javascript "access plus 1 year"
    ExpiresByType application/x-javascript "access plus 1 year"
    ExpiresByType text/javascript "access plus 1 year"
    ExpiresByType audio/ogg "access plus 1 month"
    ExpiresByType image/bmp "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/svg+xml "access plus 1 month"
    ExpiresByType image/webp "access plus 1 month"
    ExpiresByType video/mp4 "access plus 1 month"
    ExpiresByType video/ogg "access plus 1 month"
    ExpiresByType video/webm "access plus 1 month"
    ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
    ExpiresByType font/eot "access plus 1 month"
    ExpiresByType font/opentype "access plus 1 month"
    ExpiresByType application/x-font-ttf "access plus 1 month"
    ExpiresByType application/font-woff "access plus 1 month"
    ExpiresByType application/x-font-woff "access plus 1 month"
    ExpiresByType font/woff "access plus 1 month"
    ExpiresByType application/font-woff2 "access plus 1 month"
</IfModule>
<IfModule !expires.c>
    <IfModule headers.c>
        <filesMatch ".(css|jpg|jpeg|png|gif|js|ico|woff)(\?.*)?$">
        # cache 30 days
        Header set Cache-Control "max-age=2592000, public"
        </filesMatch>
    </IfModule>
</IfModule>

This will cache (non third-party) javascript as it appears in WordPress. If you have control over your server, it is probably easier to have mod_expires on, so type in:

a2enmod expires
service apache2 reload

Many servers will have this enabled by default. If not, hopefully they have headers enabled by default.

You can test your cache results using this tool.

There are few more advanced features, like gzip compression, and more advanced server setups, like Varnish/Apache, or Nginx/PHP-FPM. that you may want to implement. However, while these will speed up your site, they don’t offer you nearly the same bang for your buck in terms of obvious performance increase compared to time spent.

How to Add a WordPress theme via composer with a Private GitLab Repository

I have been exploring using Composer for managing themes and plugins for WordPress. For public themes and plugins, this could not be easier using WordPress Packagist. However, I had a hard time finding a straightforward explanation for how to integrate a theme I am developing on a private GitLab repository.

It turns out that the solution is very simple. In your GitLab theme/plugin:

{
    "name": "<username>/<package>",
    "type": "wordpress-theme|wordpress-plugin",
    "require": {
        "composer/installers": "~1.0"
    }
}

Adding composer/installers as a require library allows you to set the type attribute to wordpress-theme or wordpress-plugin.

When you are including your theme/plugin in a composer file at your WordPress root, include these configurations:

{
    "repositories": [
        {
            "type": "git",
            "url": "git@gitlab.com:<username>/<package>.git"
        }
    ],
    "require": {
        "<username>/<package>": "<version>"
    }
}

Important: For a private repository, you need to add the private key beforehand by loading it into an SSH config file or using ssh-add.

Windows Users: I recommend using VVV for testing WordPress. If, however, you want to stick with Windows and a WAMP server, you can download Git-SCM and follow these instructions to add SSH keys. I was able to set up an SSH key when running Git Bash (not Git CMD). You can also run plink.exe by following the instructions.

Your Guide to VVV

VVV, or Varying Vagrant Vagrants, is a tool which will make your life as a WordPress developer infinitely easier. After I learned about it at WordCamp NYC‘s Contributor Day, I found myself drawing a blank as to how I survived WordPress development without it.

Here are a few of my favorite features of VVV:

  • Install once, add as many WordPress websites as you want.
  • Extensions are available. Josh Lee, a WordPress extraordinaire I met at the event, told me about vv. This allows you to create WordPress installations on-the-fly.
  • Basic installation includes Stable, Developer, and Trunk so you can easily test your themes on the newest version of WordPress
  • Uses vagrant-hostsupdater and creates easy to remember host names for your base installations. I used to do this on my local machine, but this is better.
  • Built on Ubuntu. I love my Mac, but BSD is not the same as Linux, and my server runs Linux. I can use it the same as I use vagrant by simply typing `vagrant ssh`, and I can make any modifications that might exist on my server.
  • Like Vagrant, it is FREE and can run on almost any machine. All you need is VirtualBox.

So, how can you get started? VVV has made it very easy. Simply follow the instructions on GitHub and you’re good to go!