Discovering Scala

As you can probably tell from my blog, I spend most of my time coding in PHP. At work, a project came up that required I write a backend service in Scala.

Scala’s claim to fame is that it merges object oriented programming with functional programming while retaining compatibility with Java. To me it seemed like a weird mix of Ruby and Java, which is very strange because I consider Ruby to be the most dynamic language I’ve worked with, and Java to be the most static. There were some parts I liked (mostly the dynamic Ruby-esque parts), and some parts I didn’t (mostly the kludges to work around the fact that we’re still dealing with the JVM).

As the service neared its launch date, I asked a coworker (also with no Scala experience) to do a high level code review. Given my recent experience, I knew he would need a few concepts to grok the code. These are the things I told him.

Continue reading

Flexible Mock Objects with Mockery

If you use stubs and mocks in your PHPUnit tests, you may have run across some of these limitations:

  • You want to call a mocked method more than once and have it expect or return different things on subsequent calls, e.g., multiple calls to query()
  • You want to set up an expectation that mocked methods are called in a certain order, e.g., validate() before save()
  • You want to mock a method that has an argument passed by reference, e.g., MongoCollection::insert()
  • You want to mock a method that doesn’t exist, i.e., the object being mocked only implements __call()

If you have, you may be pleased to know that there’s a drop-in replacement for PHPUnit’s mock objects that supports all of these use cases. It’s called Mockery.

Continue reading

Using Stubs and Mocks in Unit Tests

In the real world, not all unit tests are as simple as

public function testAdd()
    $txn = new Transaction(50);
    $this->assertEquals(75, $txn->add(25));

For example, a controller for a page that displays tweets might have a dependency on a TwitterService object.

use Zend\Mvc\Controller\ActionController,

class TweetsController extends ActionController
    public function indexAction()
        $twitter = new TwitterService();
        $tweets = $twitter->getTweetsBy('jtai');
        return array('tweets' => $tweets);

If you tried to test this controller like the hypothetical transaction object above, you’d end up with something that looks like this:

public function testIndexAction()
    $controller = new TweetsController();

    $expected = array('tweets' => array(
      'Ate breakfast',
      'Good morning!',
      'Ate dinner',
      'Funny cat picture, lol',
      'Ate lunch',      

    $this->assertEquals($expected, $controller->indexAction());

There are a number of problems with this approach. The most obvious problem is that the correct output will vary depending on what I’ve tweeted recently. As soon as I tweet about another meal or post another funny cat picture, the test will break. A more subtle problem is that this test now depends on Twitter being available, so the test cannot be run offline. Also, if Twitter were to go down, the test would fail. Even if Twitter had perfect uptime, the test would run more slowly because it would have to make a real network request. Finally, this is no longer a unit test. The TwitterService object is being tested along with the TweetsControlller.

Continue reading

ImageMagick Engine for WordPress

I should have posted this first in my “building a photo blog with WordPress” series, since it’s the first and most basic problem I came across. It slipped my mind until now, sorry.

I had just spun up a new Ubuntu 12.04 testing instance and installed PHP from apt. I installed WordPress and started playing around with uploading photos. The problem was, WordPress wasn’t resizing my photos. It was just displaying the full-size photos with smaller height and width attributes for thumbnails. Since I hadn’t used WordPress for photo blogging before, I wasn’t sure if it was even supposed to resize images, but serving 500k+ thumbnails seemed like a bad idea. (Now that I know it is supposed to resize images, I’m not sure silently falling back on displaying full-size photos is the best idea. A warning in the admin dashboard pointing to the PHP GD extension would be nice.)

Searching for “wordpress generate thumbnails” frustratingly brought up articles about generating thumbnails for posts, which isn’t what I wanted. I wanted WordPress to generate smaller versions of images that I uploaded. I knew that WordPress would require the GD extension, the ImageMagick extension, or at least an external binary of some sort to do resizing server-side, but searching for “wordpress gd extension” didn’t turn up anything useful.

Fortunately, searching for “wordpress imagemagick” worked out a lot better. I found a ImageMagick Engine plugin that replaces the standard GD library support with ImageMagick. In my experience, ImageMagick creates better looking thumbnails, and if I remember correctly, uses less memory to boot. The plugin is also quite nice in that it provides a settings page in the WordPress admin that lets you set the image quality and regenerate thumbnails, eliminating the need for a separate plugin to regenerate thumbnails. And if the ImageMagick binary and PHP extensions are both missing, the page is very clear that you need to install one or the other.

A quick apt-get install php5-imagick and /etc/init.d/php5-fpm restart later, and I was all set!

Lazy Loading Images on a WordPress Blog

This blog is pretty bare when it comes to images, but the photo blog I’m working on has a lot of them (obviously). I have seen some other photo blogs lazy load their images to conserve bandwidth, and I wanted to add this feature to my own blog, too.

I found this WordPress plugin that does the trick, but when I looked into the code, I saw it was forcing jQuery 1.6.1 when the latest version of WordPress (3.3.1) ships with jQuery 1.7.1. I also noticed that the version of the jQuery Lazy Load Plugin it wraps was out of date — 1.5.0 vs. 1.7.1. (The jQuery Lazy Load Plugin happens to have the same version number as the version of jQuery shipped with WordPress — very confusing all around.)

Since the WordPress plugin was already on GitHub, I forked the repo with the intention of updating the plugin. I thought it would be as simple as removing the hard-coded jQuery 1.6.1 dependency and updating the embedded copy of the jQuery Lazy Load Plugin. Of course, it wasn’t that simple.

Newer versions of the jQuery Lazy Load Plugin require that you alter your HTML, because some “new browsers” (I’m still not sure which ones — Safari? or all Webkit-based browsers?) will load images even if the src attribute is removed with JavaScript. So if your original image looked like this

<img src="/images/cat-picture.jpg">

You would have to change your markup to

<img src="/images/placeholder.png"
<noscript><img src="/images/cat-picture.jpg"></noscript>

The <noscript> part is actually optional, but browsers with JavaScript disabled won’t load the images at all without it.

The existing WordPress plugin was essentially a shim to load the jQuery Lazy Load Plugin. To support the newer version of the jQuery Lazy Load Plugin, it would have to hook into various WordPress filters to modify <img> tags to add the lazy classes and <noscript> fallbacks.

After about half an afternoon of tinkering, I got all the pieces in place and had the updated plugin working on my photo blog. The regex I’m using might be a little too strict, but overall the plugin is nice and self-contained. It adds all the right CSS and JS in all the right places, so all you need to do is install and activate the plugin like before. If you’re interested, you can grab the updated code from my fork on GitHub. I also sent a pull request in case the original author is interested.