Greg Boone

Tag: php

How can I use PHP Namespaces in WordPress Plugins

PHP has long had a problem of naming collisions. Because older versions of PHP had no way of declaring methods outside the global space, developers came up with several different ways of preventing and checking for namespace collisions, none of which treated the underlying condition. These many and varied solutions begged for a unifying standard as they made things like autoloading and package management increasingly difficult. PHP 5.3 introduced a feature called ‘namespacing’ to solve this problem and WordPress developers should begin adopting. With proper namespacing, WordPress plugin and themes will become clearer, more stable, and more portable.
<!–more–>

Prior to PHP 5, if you tried to name a method or class foo it might conflict with another similarly nammed method elsewhere in the system. Developers came to terms with this by ‘namespacing’ methods with a prefix. With this standard, foo became my_foo or gb_foo where the my_ or gb_ corresponded to vendor prefixes (gb, being my initials). It also led to wrapping every method in a conditional to check for namespace collisions:

if ( !function_exists(gb_foo) ) {
    function gb_foo( $bar ) {
        echo $bar;
    }
}

gb_foo('bar');

Look familiar? The problem with this should be easy to see. If that conditional returns false, my method `gb_foo` will never be fired and any time it’s called, that other `gb_foo` method will. Imagine if `gb_foo` was something like this:

function gb_foo($bar) {
    mysql_query('DROP TABLES *');
}

I think we can all agree that would be bad.

Namespacing is a concept familiar to many other programming languages that isolates your application from others in a standardized way. The global space should be reserved for only those things that should be available at all times. There is typically a character or pair of characters which globally signifies a namespace separator. In PHP it’s the backslash .

If properly namespaced, you can name your method foo() without any possibility of your method conflicting with anything else (unless you declare it twice in the namespace).

Namespacing also alleviates your need to wrap your methods in that conditional. A properly namespaced foo() method would look like this:

namespace gb;

function foo($bar) {
    echo $bar;
}

Let’s take a look at what’s going on here. On the first line we declare the namespace we want to use, in this case my initials gb. We can then declare classes and methods without worrying about stepping on any other methods. This is sort of like putting things in classes, but it’s even more safe. To call that ‘foo’ method, just type gbfoo('baz'); which should output ‘baz’. You can also declare classes inside the namespace just like you would normally, the difference is that when these are called, the namespace must be too. There are a few different ways of approaching this:

Consider the application lives in a file called test.php and all our files are in the same directory.

// test.php
namespace gb;
class Bar {
    public static function foo($bar) {
        echo $bar;
    }
}

Example one: ‘Use’ the namespace, declared at the top of the second file.

require_once(DIR . '/test.php'); use gbBar;

Bar::foo('baz');

Example two: Call the method with the namespace and class prefixed.

require_once(DIR . '/test.php');</p>

gbBar::foo('baz');</p>

Example three: Instantiate the class as an object and declare the method from the object.

require_once(DIR . '/test.php');</p>

$object = new gbBar();

$object->foo('baz');

They’re all very similar and should look familiar. Again, all the namespace does is add a layer of abstraction away from the global space in order to prevent collisions. Where it becomes particularly useful is in autoloading with tools like composer. With namespaces autoloaded, developers do not even need to require the files where those classes exist. They only need to know the namespaces. Example one, then, becomes:

use gbBar;
Bar::foo('baz');

Pro tip: you can ‘use’ a namespace under another name. So if you have two classes Bar, you can redeclare them like this:

use namespaceBar as Bar;
use gbBar as Baz;

Baz::foo('bar');

You can also stack namespaces to isolate your individual plugins from each other: namespace gbmyAwesomePlugin; and namespace gbanotherAwesomePlugin serve as different namespaces for different plugins. It also keeps me safe from other ‘gb’s out there crowding my namespace.

Namespaces can also indicate where to find your application. With a fully namespaced plugin, you could even configure your WordPress install to use your plugin without ‘installing’ it. If you have composer doing that for you, you can autoload the plugin preconfigured the way you want it. WordPress is becoming an increasingly vibrant application development platform and namespacing will be key to it living in harmony with other PHP applications in complex systems.

Writing Unit Tests for WordPress

This post and others like it still get a strange amount of traffic. It’s worth noting the details here are out of date and I won’t be keeping it up. Use at your own risk!

In my last post I wrote about two testing libraries for WordPress and briefly discussed the difference between integration tests and unit tests. I also mentioned a concept called test driven development (TDD) and breifly explained how it might help write better code from the start. This post will expand on that and show how to write a simple WordPress plugin from a test-first approach. Since we’re writing unit tests, we’re going to use WP-Mock to create a test double for us and we’ll use PHPunit for our test runner.

TDD starts with a problem you want to solve—the same problem your plugin wants to solve. In this case, let’s say we have a plugin that will add some metadata to a post with the title “Test”. Since that’s going to require us to mock some WordPress core functionality, make sure WP-Mock is configured in your working environment. We’ll start by writing a test that verifies the metadata was attached to the post.

In order to write unit tests we first need to extend the base test suite:

Class OurTestSuite extends PHPUnit_Framework_TestCase {

}

Now that we have a class, we can call any of PHPunit’s methods for testing including all of its assertions. Inside OurTestSuite is where we will write all our testing methods. We start with setUp and tearDown, commonly named methods that instantiate some conditions we will want for all our classes. We’ll want to make sure our setUp and tearDown methods clean up our test environment as well as any mocks we create out of WP_Mock. So we’ll declare:

public function setUp() {
         parent::setUp();
     }
     public function tearDown() {
         parent::tearDown();
     }

If we had other objects, variables, or settings we wanted available throughout the test suite, etc., we could declare those too. If you run the test now you’ll get some output, but no tests will run because we haven’t written any. Every test is a method within this class. Let’s write one that will always pass just to see PHPunit give us something.

...
     public function testOneExpectsOneAdded() {
         // Arrange
         $foo = 1;
         // Act
         $bar = $foo + 1;
         // Assert
         $this->assertEquals(2, $bar, 'Variable $bar does not equal two.');
    }

If you run PHPunit on that test, you should get a dot. Congratulations!

Now let’s write our test for our save_meta method. There are three basic sections to our test: Arrange, Act, and Assert. The first section is for all the bits our method needs for input. In our case, we’ll need the post ID for a post called “Test” and a key and value pair to save as metadata. Since the ID could be any integer on a given system, we can arrange our test with any integer we like. The next piece, the key-value pair, will be set in the method, but we’ll want to decide now what they’ll be.

The “Act” section is where we call the method. In this case, we’re going to call a method called save_meta_data out of the MetaMethods object. Finally, the “Assert” section is where we decide what the method should expect to see at the end. This section might be empty depending on whether the method under test returns an output or calls some other method. In our case, it’s the latter. The test passes if update_post_meta is called exactly once. Right now our test is looking something like this:

...
     public function testTestPostExpectsMetaDataSaved(){
         // Arrange
         $post_id = 42;
         // Act
         $methods = new MetaMethods();
         $methods->save_meta_data($post_id);
         // Assert
    }
...

Not a bad looking test, but we have some mocking to do. We already know we’ll need to mock update_post_meta(), but we’re also going to need get_post() as well. In both cases, we’re going to make PHPunit handle calls to those methods and return what we want back. We know what to expect if we call update_post_meta: if all is well with our WordPress install, we expect it would add new information to the post object. So we don’t need to verify that, all we really need to do is verify it’s being called exactly once. So let’s add our mocks to the “Arrange” section.

Fully mocking a function like get_post() uses the static method wpFunction() from WPMock. We can call it with: `WPMock::wpFunciton(). We can also pass wpFunction some parameters like ‘times', for how many times we expect the mocked function to fire, and ‘parameters', and ‘return'. These help us create a fully function test double ofget_post`.

...
// Arrange
$post = WP_Mock::wpFunction('get_post');
...

Finally, we need to address update_post_meta, but since we don’t particularly care what we get back from this method, we can instead ‘stub’ it. WP_Mock has a wrapper for wpFunction that make this easy, it’s called wpPassthruFunction() and can take many of the same parameters, but fills in the return value for you. In our case, we want to know that update_post_meta fired once, so we can write something like:

...
// Arrange
WP_Mock::wpPassthruFunction('update_post_meta', array('times' => 1));
...

Now, if we run phpunit, we get a dot and an F, or maybe an E, since we haven’t written any code yet. Now we can write the actual code with the following workflow:

  1. Write some code
  2. Run the test
  3. Modify the test and code as necessary
  4. Repeat 2-3 until the test passes

A full example of our test is below:

Class OurTestSuite extends PHPUnit_Framework_TestCase {
     public function setUp() {
         parent::setUp();
     }
     public function tearDown() {
         parent::tearDown();
     }
     public function testOneExpectsOneAdded() {
         // Arrange
         $foo = 1;
         // Act
         $bar = $foo + 1;
         // Assert
         $this->assertEquals($bar, 2, 'Variable $bar does not equal two.');
    }

    public function testTestPostExpectsMetaDataSaved(){
        // Arrange
        $post_id = 42;
        $post = WP_Mock::wpFunction('get_post');
        WP_Mock::wpPassthruFunction('update_post_meta', array('times' => 1));
        // Act
        $methods = new MetaMethods();
        $methods->save_meta_data($post_id);

        // Assert
    }
}