WordPress in the Enterprise – Building in a Class Library

When you think of WordPress you might think of a lone blogger blogging about what they ate for lunch. But that is just not true anymore. With nearly 31% of the web under its control, WordPress has gained a lot of popularity due to its easy setup and extensibility. It has become a powerful Content Management System (CMS) that even an enterprise can build epic sites off of. But if you have a lot of proprietary code from your existing site that you can’t just dump into the ether, how can you begin incorporating that into a new instance of WordPress? How can you tie in your existing classes into the platform in such a way that it can be used across themes, your own custom plugins or to extend your templates? In this article I will show you a great technique I have used that has given me maximum flexibility to incorporate a company’s existing PHP classes… and it is ridiculously easy to implement!

First Thing, Organize the Library

The first step is to make sure you have a place to gather up all of your classes (if you haven’t done that yet in your other platforms). These should be high level reusable classes that transcend a given site. They are classes that might tie into 3rd party services or domain specific to your business (aka business logic). One place I often use is a special folder one level up from the website’s document root (aka web root) and I call “lib”. I found that this is the perfect place to protect your company’s proprietary code.

Since this directory is out of the web root, it is not publicly accessible on the web and so doesn’t need any special guard conditions like if (!defined(‘ABSPATH’)) at the top of your class files. They can also be centralized to a single location and easy to find for PHP. Remember that while not in web root, PHP can still reach up and into this folder to pull in the classes when needed. Also being outside of web root means that you could in fact access and reuse the classes across multiple web projects without having to dig into another site’s file structure. In addition to this, as a quick tip, you should make sure the file names match a specific pattern. This will become important later. For my classes I use the pattern “class.ClassName.php” and then name the class itself “ClassName”. These ideas are expressed in the image below…

Now with the classes in a single location, we have one last thing to check. We must make sure that each class can stand on its own and that any dependencies are fully injected into the classes as required. For instance, a class that uses a database connection should not instantiate that connection directly (or if it does, it uses another class that can be found in the local library but this is not ideal). Injecting classes by passing them through a class’ constructor is always preferable. If you are coming from another CMS platform, check for this carefully since classes will now want to be working with WordPress’ $wpdb database object.

Adding the Autoloader

Since we have the classes setup and in a central repository of sorts, we can tell WordPress / PHP where to find them. We will do this via an autoloader function. But how do we tie this in for maximum flexibility? One process would be to call the autoloader from a really early WordPress hook like muplugins_loaded. However, I found it slightly better to construct a must use plugin (mu-plugin) which consists of a single file and contains the single autoloader function. I do this for a few reasons:

  1. It gives the tie-in a nice name (since you can name the plugin) and this name will be visible from the must use plugin section of the WordPress admin.
  2. It will be loaded slightly earlier than even the muplugins_loaded hook. Named appropriately (must use plugins are listed alphabetical) it could even be loaded before other must use plugins and make the classes available to those as well.
  3. It can be edited, changed or disconnected independently from everything else. Think of it as a nice little connector plugin between WordPress and your class library.

Besides these reasons, the autoloader code will not get lost in a sea of hooks buried in some functions file or theme file that may be unloaded later. Here is how the plugin file can look:

<?php
/**
 * Plugin Name: Company's Custom Library Connector
 * Description: Links WordPress to a class library for my company.
 * Author: Your Name
 */

spl_autoload_register(function($class)
{
    $dir = "/path/to/lib/folder;

    $file = 'class.' . str_replace('\\', '/', $class) . '.php';

    $path = $dir . DIRECTORY_SEPARATOR . $file;

    if (file_exists($path)) {
        require_once $path;
    }
});

Ok, but What is an Autoloader Again?

The reason for the autoloader, if you are not familiar with them, is to allow PHP code to dynamically locate and load classes when they are first encountered in the code and only when needed. When you reference a class, PHP will call the autoloader to find out where the class file is located (for us this will be the lib folder we created earlier) and loads it. This gets around the need to specify “include statements” at the top of files. Since files are only loaded when needed, it will improve page loading, prevent exposing code that shouldn’t be on a page and rids you of the burden of needing to keep track of include statements that may or may not be even used. Autoloaders are always a good practice when you can use them.

For example, if you have a custom instance of SugarCRM that your company uses to keep track of customer data, perhaps you have a PHP class that wraps around its API. You would put this class in your lib folder and then write code that just uses it…

// No include statement, just use it. Autoloader will go find the class and include it.
$crm = new sugarCRMClient($username, $password); 

// Do stuff with $crm

Conclusion

Now that we have a library setup with properly named class files, then loaded via a must use plugin appropriately named, we have a solid solution for automatically calling and loading in a proprietary class library for use in themes and plugins you create. Since we have these classes in a folder one level up from web root, we also prevent these class files from being loaded directly and make them reusable for other sites or projects. You should find this is a great start for integrating any kind of proprietary class library your enterprise may already have in place. Next it will be up to you to write the functions and themes which can take advantage of these classes. All you will need to do is just call on them. In our next article we will cover where to put your classes and functions that are theme specific. You may know about the functions.php file, but how do we prevent it from becoming unmanageable?

Interested in testing out your new found knowledge or looking to practice with some projects? Checkout out our ebook titled “The Programmers Idea Book“. It contains over 200 project ideas, tips for solving them and has a difficulty rating so you know what you are getting into. Thank you for reading! 🙂

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 25 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.