How to Unit Test a CakePHP Console (Shell) Command — An Example

Wow, it sure took me a long time to find an example of how to write a unit test for my CakePHP console (shell) commands. There’s no how-to in the CakePHP documentation, and the only blog post I could find was this thing from 2009 and a correspondingly outdated version of the software.

I eventually found some code on github that Mark Story himself had written for a side project, and using that I was able to put together a bare-bones example of how to write a unit test for a CakePHP console (shell) command.

I deliberately wrote a really dumb shell to test because I just wanted to see that a test could be written. I figured, once I had the pattern I could write more sophisticated tests.

Anyway, if you’re stuck like I was, please follow along.

Step 1: create a really dumb console

Create a file called ThingyShell.php in this folder of your CakePHP application:  /app/Console/Command/

These are the contents. (Later, we’ll test the method called getFour().):

class ThingyShell extends Shell {
    public function main()
        $four = $this->getFour();
    public function getFour()
        return "4";

Step 2: make sure your console runs

I wanted to make sure I didn’t include any dumb errors in my dumb shell, so I  ran the console locally to ensure it works:

C:\[...etc...]\app>cake Thingy

Welcome to CakePHP v2.7.0-dev Console
App : app
Path: C:\[...etc...]\app\

Step 3: create a test file

Create a file called ThingyTest.php in this folder of your CakePHP application:  /app/Test/Case/Console/Command/

These are the contents:

App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('Shell', 'Console');
App::uses('ThingyShell', 'Console/Command');

class ThingyTest extends CakeTestCase
    public function setUp()
        $out = $this->getMock('ConsoleOutput', array(), array(), '', false);
        $in = $this->getMock('ConsoleInput', array(), array(), '', false);
        $this->Thingy = $this->getMock('ThingyShell', 
            array('in', 'err', 'createFile', '_stop', 'clear'),
            array($out, $out, $in)
    public function testGetFour()
        $expected = "5";
        $actual = $this->Thingy->getFour();
        $this->assertEquals($expected, $actual);
    public function tearDown()

You should now be able to navigate to your tests and run Console / Command / Thingy.


You should see a nice failure message like this one:


A few comments

The getMock() method comes from PHPUnit, not from CakePHP. Mr. Story explains the parameters on a blog post from 2010.

Essentially, the ThingyShell getMock is saying: replace the methods called ‘in’, ‘err’, ‘createFile’, ‘_stop’, and ‘clear’ with the variables offered on the next line. And those variables are empty mocks of ConsoleOutput and ConsoleInput.

Any methods not replaced will run on your real ThingyShell object.

Once you’ve got this proof of concept working, you should be able to expand on it to write real unit tests on your real console shells.



Posted in CakePHP, Testing | Leave a comment

Why Doesn’t XDebug Work? It Used To.

I found myself asking (again) why XDebug wasn’t working, after installing a new IDE. I’d set a breakpoint, debug the page, but never see the code stop.

I had trouble getting it to run the last time I tried a new IDE, but I didn’t remember exactly what the problem was. This blog post is to remind me how to quickly get XDebug up and running correctly in a new IDE.

Short answer this time: XDebug is usually attached to port 9000. (You set this in your php.ini file.) If it isn’t, or if something else is attached to that port, you can move it, but you have to change both the php.ini file and your IDE’s configuration for where it expects to find XDebug.

This StackOverflow question got me thinking in the right way.

This flowchart from Netbeans also helped me. It pointed me to the excellent tool published by the XDebug folks.

And now that I’ve made a note of how to get myself back up and running in the future, I’m going to make a small donation to XDebug because I do indeed find it useful.

Posted in Debugging, PHP | Tagged , , , , | 2 Comments

What’s the deal with wp_enqueue_style (and why does WP documentation suck?)

I’m implementing a child theme for the WordPress template twentyfourteen.

I followed the simple directions at WordPress’ Child Themes page.


I finally got override styles to show

Yet my styles were not showing up. Not only were they not overriding the parent styles, Firebug showed that they were not even getting to the page.

Well, I wasn’t entirely confident about how I implemented my child themes. WordPress’ incomplete instructions said:

If your theme has more than one .css file (eg. ie.css, style.css, main.css) then you will have to make sure to maintain all of the Parent Theme dependencies.

… whatever that means. Then they then include this undocumented sample code:

add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );

Notice that the WordPress team never explained what literal string you should use instead of  ‘parent-style’ — I assumed I should use ‘twentyfourteen-style,’ but I was just guessing. Maybe ‘twentyfourteen’ would have been correct, or maybe the name of the style was some other string that you have to look up somewhere.

I spent far too long looking for the missing documentation when finally I decided to forge ahead with trial and error.

Here are the results for what to use instead of ‘parent-style’:

When I used ‘twentyfourteen-style’

My styles did not show up. Firebug showed me that 6 css files were served to me, including blog/wp-content/themes/twentyfourteen/style.css?ver=4.2.2

When I used ‘anything-else-like-my-child-theme-name-or-jsldfkjsdlfkjsldkjw-or-even-literally-parent-style

My styles did show up. Firebug showed me that 7 css files were served to me, including blog/wp-content/themes/twentyfourteen/style.css?ver=4.2.2 and blog/wp-content/themes/mythemename/style.css?ver=4.2.2

So the short answer is that you should use the literal string “parent-style” in WordPress’ sample code. The only string you can’t use is ‘[yourParentThemeRealName]-style’ because then you will not actually see your override styles.

I did dig a little deeper and discover that the first parameter to the function theme_enqueue_styles is a key of sorts. Whatever name you give as the first parameter is the name of the “key” that WordPress uses to handle overrides. So if you use the same name twice, only the first occurrence will stick.

I used this to my advantage. I enqueued “a-different-unique-string-name” to include a secondary style sheet that I was already using elsewhere. As long as I used a unique name, I would get my child theme’s CSS file, as well as all the others that I stacked up in my queue.

Here’s the contents of functions.php that I ended up with:

add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles_viewpoint' );
function theme_enqueue_styles_viewpoint() {
        get_template_directory_uri() . '/style.css' 
        dirname(__FILE__) . '/../../../../resources/styles/anthemize.css'



Posted in CSS, Webmastering, WordPress | Leave a comment

Simpler than WordPress — or is it?

“Hey, Mart, can you post the latest newsletter to my web site? By the way is that something I can do easily?”

I have many clients for whom I’ve built web sites. I usually try to let them make updates themselves through an admin interface, but even then, some clients would rather have me do the work.

For some people, updating their web site is about as fun and relevant to their job as filing taxes.

So what do you do when a client wants to be able to make changes to documents, or launch a blog, or post newsletters on their own web site?

WordPress to the Rescue (*assuming you drank the WP Kool-Aid)

I know many advocates of WordPress who say it’s just as easy to use as Word or Pages. They recommend it to all their clients. In fact, here I am on a WordPress site. And yet, I have a hard time recommending it for some of my clients, for many reasons:

  • wordpress interfaceInterface overload can be intimidating for someone who just wants to publish some text. As I type I have a sidebar with 8 options; I see two icons above the sidebar that I don’t necessarily understand, as well as a few cryptic buttons. As a computer professional, I don’t find them intimidating, but to someone who doesn’t know what’s okay to ignore, it’s more cognitive load.
  • WordPress requires an installation, of code and database.
  • WordPress is popular among hackers and spammers — just the sort of security risk most of my clients don’t want to think about.
  • WordPress doesn’t easily integrate with an existing design. Someone has to spend time customizing WordPress templates to sort-of match a site’s design.
  • WordPress does HTML structure how it likes to which means your blog and your site may not look exactly the same, and they may not share CSS and JS, requiring twice the effort for every update.

Don’t Start with a Hammer

Some would say that WordPress is a great tool. But when your favorite tool is a hammer all your problems look like nails.

Rather than recommending yet another unnecessary WordPress installation, I asked, what is it that my “newsletter client” was already doing? And how can we painlessly integrate that into her web site.

Well, she had written a newsletter in Pages. There was minimal formatting — a headline, paragraphs, one link, and a photo. She created a document, pasted a photo and e-mailed it to  her friends.

Would there be some way to write a document, without all the overhead of WordPress, and include it on a web site?

Of course there is.

Markdown is Simple

One of the best experiences I had editing a document on a web site was submitting a correction to the CakePHP documentation. The documentation is hosted on github. When you find a page you want to edit, you click a button that opens the page’s Markdown source. You make whatever changes you like, then submit your version of the doc to be reviewed, merged, and published.

Because it’s markdown, you can’t inject any malicious code. You can’t ruin the structure or the design of the page. You can only add text, with basic formatting. So unless you type gibberish, you really can’t do much to break the site; you are just adding content.

wordpress structure

WordPress’ HTML structure isn’t exactly “Simple”

Markdown’s resulting HTML is simple and clean, unlike what comes out of WordPress. It plays nice with whatever template and style sheet you’ve already defined.

For my client to save her newsletter as Markdown would be a simple matter of exporting her already-written document as plain text, and cleaning up three things –

  • adding # before the headline,
  • changing her link to [link text](url) format,
  • and changing the photo to ![Happiness Unshared](myphoto.jpg).


If she creates an .md (markdown) text file, it’s still not on her web site. Should she FTP the file into a special folder? That sounds like as much trouble as WordPress with even more risk.

What about hosting the documents on github? Well, it’s a nice idea but their system is entirely set up for hosting documentation. It’s not really usable for ad-hoc web sites.

However, the idea of committing code to a repository and pushing it seems like it might be pretty easy, especially if we find a very user-friendly program like Tower or SourceTree. She doesn’t need to know about source code or how git works, she only needs to know that she checks in her new newsletter when its done, and clicks Push when she’s ready to launch. (We already have an auto-deploy script running). Fixing a typo is as simple as editing the document and re-pushing it.

I think it could be easier and cleaner and less risky than WordPress. But I admit this could be one of my crazy ideas that’s more dumb than inspired.

I’ll visit my client on Friday and show her both options. We’ll see what she thinks.

Posted in Uncategorized | Leave a comment

Hey WordPress, where did you hide the logout button?

Just posted on my completely standard WordPress blog. I did not customize the admin interface, this is just exactly as it comes, out of the box.

Now where in the hell is the logout button?

Here’s where I’ve looked so far:

How do I log out, WordPress?

How do I log out, WordPress?

… I know I could probably figure out the URL, but what the hell? Where is it?


UPDATE – I found it. It’s in the little blank gap between the pencil and the word balloon.


“Blank gap” you ask?

Yes. Apparently regular people who do not block third-party trackers see a little circle served by Gravatar.

Those of us who are more privacy-minded, we get a blank spot.

Is Gravatar a privacy risk? StackOverflow says yes.


Posted in Uncategorized | 2 Comments

Ical and Daylight Savings time in PHP

The film festival I volunteer for is usually in February, but this year it takes place during the same weekend as the switch to Daylight Savings time.

For a 7-hour window before Daylight Savings Time, my iCal events were off by an hour

For a 7-hour window before Daylight Savings Time, my iCal events were off by an hour

Years ago I built a link on each detail page that lets you add the movie to your calendar via ical.

I actually did pretty well. I remember time zones being a huge pain, but whatever solution I ended up with worked for years. Even this year, most of the events are correct. I don’t know whether I wrote this function or found it, but it is the magic bullet.

private function unixToIcal($uStamp = 0, $tzone = NULL) 
    if ($tzone === NULL)
        $tzone = date("Z", $uStamp);
    $uStampUTC = $uStamp - ($tzone);
    $stamp  = date("Ymd\THis\Z", $uStampUTC);
    return $stamp;       

Unfortunately, starting with the 7:15 show on Saturday, the times are off by 1 hour. The 7:15 p.m. show gets added to your calendar at 8:15 p.m. And the 9:30 p.m. show is added at 10:30 p.m.

Astute readers will notice that the $uStampUTC variable is calculated by adding a difference between the (local) event time and UTC.  The problem is that at the time of the event — $uStamp — Daylight Savings has not happened yet. But at UTC time of the event — at $uStampUTC — Daylight Savings has begun.

After some thought and some debugging, I found a way to do this without adding and subtracting 7, but rather letting the computer do all of the adjusting.

Check the new improved method here:

private function unixToIcal($uStamp = 0) 
    $revert = date_default_timezone_get();
    $stamp  = date("Ymd\THis\Z", $uStamp);
    return $stamp;       

I love it when a fix is shorter and simpler than the problem. In this case, we take the event time — $uStamp. Rather than converting time zones ourselves, we let PHP convert to UTC for us at the same time as it formats the date in ical format with:


Then just to be polite we revert back to the system’s time zone.

Posted in Debugging, PHP, Web programming | Leave a comment

function dry(){echo “Do not repeat yourself”;} dry(); dry(); dry();

Jumpy Thumbnails

It was a snowy Saturday morning and I didn’t have a lot of pressing matters, so I decided to track down a silly issue, off the clock, for a client of mine. On two similar pages, the space below a group of thumbnails was different. The thumbnails were <img> tags wrapped in <a>tags, inside a <td>.

I started by using Firebug to see what styles were applied to the various elements on the page. I expected the padding or margin on either the <img> or <a> would be different between the pages.

Firebug showed that there were no differences in the applied styles, even though clearly there were differences on the page. Firebug even “admitted” as much by showing one <a> element grayed out, and showing the other one active. In Firebug, a grayed-out element means that means that it is not displaying. But again, the applied styles were identical, and on both pages the <img> tag were displaying. I noticed that page with the grayed-out <a> tag had less space — in fact, the <a> occupied no space at all, (implying a float? or zero height/width?) where on the other page, the <a> had dimensions.

Obviously it wasn’t a style issue since Firebug reported the CSS being identical. I decided to look at the raw HTML source code (which is generated by PHP) and discovered that one image contained the meaningless “align=’bottom'” and the other contained the equally meaningless “align=’left'” — I say “meaningless” because once you use CSS style sheets, they generally control the alignment, and not these HTML attributes.

Nevertheless, I removed them both. Sure enough, things started lining up.


There is actually a larger problem at work here. Because why should there be two, different, meaningless ways of doing the same thing?

The code that I found (but didn’t write) repeats two (slightly) different versions of the same 60-100 lines of code. What I found was something like this:

if (logic for top level page)
    // 60 lines of code to draw thumbnails
} else if (logic for sub-level page) {
    // 60 lines of code to draw thumbnails
    // 40 lines of code to do some other stuff

This is what is known as a Bad Practice. Once you write 60 lines of code, when you need to do the same thing again later, you don’t copy and paste those 60 lines. You encapsulate them and re-use them. If you need to modify 5 lines, you separate the 5 lines that are different and you reuse the 55 that are the same.

Because when you don’t, you end up making a change to one (“align=’bottom'”) that you forget to make to the other (“align=’left'”).

And you end up with a finished product that is buggy and inconsistent and difficult to fix.

Humbleness Disclaimer

This sort of programming mistake really frustrates me. I spend hours debugging some stupid flaw that, really, is hardly worth fixing. I mean, 4 pixels of white-space difference should not be worth an hour of my time. (In fact, I didn’t bill my client for this fix because my professional advice would have been to save their money.)

If the code had made use of a “drawThumbnails()” function, this wouldn’t have been an issue. If the pages are supposed to look the same, they should be made from the same mold. This is why “DRY” (Don’t Repeat Yourself) is an important rule for programmers.

And now that I’ve finished my rant, I’d like to acknowledge that somewhere, out there in the wide Internet, is a post just like this one, written by some poor programmer who inherited my awful code from five years ago.

To you, I apologize. I am always learning and always improving. Unfortunately that means that stuff I wrote years ago is guaranteed to be embarrassing today. Maybe I didn’t get enough time to finish the project well, maybe I was swamped with other work and had to leave well enough alone. Or maybe I was just younger and dumber and there are no excuses. Hopefully you’ll forgive me rather than curse my name.

Let’s all agree to write better code, not release anything that isn’t ready, and not be too hard on the developers who came before us.


Posted in Refactoring, Web programming | Leave a comment