Making Testable Static classes

If you’ve ever tried to subclass a PHP4 static class you may have come to same conclusion that I have its a total pain in the neck. However, I think I’ve come up with a not too terrible approach.

Show Plain Text
  1. function &getInstance() {
  2.     static $instance = array();
  3.     if (!isset($instance[0]) || !$instance[0]) {
  4.         $args = func_get_args();
  5.         if (!isset($args[0])) {
  6.             $args[0] = 'FireCake';
  7.         }
  8.         $instance[0] =& new $args[0]();
  9.     }
  10.     return $instance[0];
  11. }

Basically the first time you call getInstance() you can specify a different name to store as the instance. And yes this can lead to people busting up your class and breaking their application. However, it also means you can effectively test the class as well. Which to me is a big advantage, and negates the possible stupid user factor.

DebugKit updates

Progress is being made on the DebugKit. It no longer smashes custom View classes and ThemeView. Thanks to Andy Dawson and Nate Abele for helping out with that. Also RafaelBandeira forked the project and supplied a library agnostic Javascript file. So that will be the standard library going forward. So big thanks to everyone who has helped so far.

Before any one asks what FireCake is. I’ve begun working on an implementation of the FirePHP library for CakePHP. It will ship with the DebugKit when complete. And there will be a FirePHP helper included as well, so when making non HTML requests all your debug toolbar information will be available in Firebug.

Comments

Ooh… The FirePHP thing is looking really sexy… FYI though your syntax highlighter seems to be broken.

anonymous user on 11/21/08

Jonah: Fixed :) My textile parser is picky about multiline code blocks. If it misses so does the highlighter.

mark story on 11/21/08

FirePHP will be really useful, I’m sure!

Does these changes mean that it will output css and js to $scripts_for_layout so it won’t break when using for example AssetHelper?

anonymous user on 11/21/08

Oscar: Currently because of the order of callbacks in the View class the scripts are not added to $scripts_for_layout. As such the the CSS and JS are added in a postRender() callback that only exists in DebugView. This callback runs after the view is finished rendering. I’m not too familiar with AssetHelper but if you are using the library agnostic JS file you shouldn’t experience any issues undefined $ functions, as it doesn’t use them.

mark story on 11/22/08

Great!
I can’t wait for FireCake. Thanks for this contribution in advance :)

anonymous user on 11/27/08

Comments are not open at this time.