Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

Monkey patching in PHP with Patchwork

Patchwork is a PHP library that allows you to change user defined functions at runtime. This can be incredibly handy when testing. I’m by no means a Ruby expert but I heard that in the Ruby world they do this kind of stuff all the time during testing.

Here’s a simple example of what Patchwork can do:

function myCounter($array)
    return count($array);

myCounter([1, 2]); // returns '2';

//now let's change the function
Patchwork\redefine('myCounter', function($array)
    return count($array) ? 'a lot of items' : 'empty';

myCounter([1, 2]); // returns 'a lot of items";

Read the implementation docs to learn how this works behind the scenes.

Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band.