Creating test doubles in pure PHP

The PHP world is not known for good unit test coverage. It’s mostly a cultural issue, but there is a technical aspect to it as well.

PHPUnit allows you to create mock objects, but that assumes your codebase uses the Depedency Injection pattern. If not, it’s very hard to add unit tests without doing major refactorings, because the language doesn’t support monkey patching (i.e. redefining functions and methods at runtime).

You could install the runkit extension, which allows you to replace everything, including constants. However, that means that anyone who wants to run the tests needs to re-compile their PHP.

Patchwork is a PHP library that makes it possible to redefine user-defined functions and methods at runtime, replicating the functionality of runkit_function_redefine in pure PHP 5.3 code.

I started using it to create mocks and it’s great, but I had this nagging thought: how the hell does it work?

I set out to figure out what black magic the author uses, only to find that he already wrote a very easy to understand description of the implementation, like any responsible developer would. Neat!

Gems like these are few and far between in the PHP ecosystem, but they do exist.

The Martin Luther Of Science

Science (from Latin scientia, meaning “knowledge”) is a systematic enterprise that builds and organizes knowledge in the form of testable explanations and predictions about the universe.

Most people, whether religious or not, agree that the scientific method, as described above, is a Good Thing.

Unfortunately, since the nineteenth century, the scientific method has been tightly coupled with a belief system called materialism:

In philosophy, the theory of materialism holds that the only thing that exists is matter or energy; that all things are composed of material and all phenomena (including consciousness) are the result of material interactions.

The main thesis of Rupert Sheldrake’s book, Science Set Free, is that science is being held back by this dogmatic belief in materialism. Below is a TED talk in which he summarizes the book, much better than I could:

In an ironic twist, the above video was banned from the official TED channel, proving that some ideas are taboo and will be deemed “unscientific” by the establishment, evidence be damned.

Pronouncing English Vowels

It’s a well known fact that, in English, the way a word is spelled can have little or no relationship to the way it’s pronounced. As a native speaker of Romanian, which is a phonetic language, I find the pronunciation of single vowels particularly confusing.

To illustrate, here’s a completely non-scientific correspondence between what an English speaker thinks he’s saying and what my brain translates it to:

Letter What I hear
A EI
E II
I AI
O ĂU
U IU
Y UAI

Because of this, my chances of ever winning a spelling bee contest are severely handicapped.

Math is not important. It's fun!

A Mathematician’s Lament is this poignant essay 1 from a few years ago that I just discovered. I highly recommend you go read it now, because I’m going to give spoilers.

In the introduction, the author makes the case that mathematics is a misunderstood art form, where the medium is imaginary objects (such as numbers and the patterns they form), instead of paint or marble. It’s not science, since it doesn’t try to understand reality, bur rather made-up things, like triangles and curves. It’s not engineering, since the focus is not on making something useful. Any practical benefit that arises from doing math is just an added bonus.

With this mindset, the author then goes on to decry, in a rather entertaining way, the horrendous state of math education. 2 In short, the system is focused on all the wrong things (notations, definitions, formalisms) and none of the right things (natural curiosity, intuition, elegance, context).

So, while sir Ken Robinson was completely right when he said that schools kill creativity, in the case of math, the education system did such a good job, for such a long time, that the common wisdom is that there isn’t any creativity in mathematics to begin with. Or that you have to be a genius to enjoy doing math.

Before reading this essay, I had this vague guilt for completely losing interest in math in high school (and, consequently, barely making it through the math courses in college). I think I can relax about it now. I would still like to learn, but not because “I might need it someday” and not even because it might make me a better programmer. Just because it might be fun.

  1. It seems it was later expanded into a short book.

  2. The author is from the USA, but I had an essentially identical experience as a student in Romania, so I’m going to assume that it’s pretty much the same everywhere.

Getting the class name from an object instance

I was recently assigned to work on a node.js project — a first, for me. I discovered that it comes with a neat CLI debugger built in, which is very handy when diving into an unknown codebase. However, when inspecting a variable, it doesn’t show me its type; only its value.

First, let’s see how you would get the type of an object in other dynamic languages.

In Ruby, every object responds to a class message, which returns an object of type Class, which responds to a name message, which returns a string:

obj.class.name

In Python, every object has a __class__ property, which contains a type instance, which has a __name__ property, which contains a string:

obj.__class__.__name__

In PHP, there’s a special get_class() function which returns the class name of an object as a string:

get_class($obj);

In JavaScript, every object has a constructor property, which contains a Function object, which has a name property, which contains a string:

obj.constructor.name

Update: Got a link on twitter to a much more in-depth discussion on StackOverflow, with various caveats and workarounds. But for getting a general idea of what kind of object a variable is, I think the above method is good enough.

When we are debating an issue, loyalty means giving me your honest opinion, whether you think I’ll like it or not. Disagreement, at this stage, stimulates me. But once a decision has been made, the debate ends. From that point on, loyalty means executing the decision as if it were your own.

Colin Powell

Posts 2 Posts: Version 1.6

There were some improvements commited to the development version of the plugin for a while and I thought I’d do a quick release, to get them in the hands of users.

With version 1.6, P2P development will effectively be entering hibernation mode. I won’t be working on any new features or bug fixes, since the plugin already works well enough on the single site where I use it. Also, I won’t be answering support questions anymore; sorry.

Of course, I’d be happy to review and merge pull requests that people open and still hope that I’ll eventually be able to hand it off to someone else.

Ruby equivalents to PHP’s foreach

In PHP, array keys can be either numbers or strings, whereas in Ruby associative arrays are a separate data type, called a hash.

Here’s a cheatsheet for various foreach variants, translated into idiomatic Ruby:

Looping over a numeric array (PHP)

$items = array( 'orange', 'pear', 'banana' );

# without indexes
foreach ( $items as $item ) {
    echo $item;
}

# with indexes
foreach ( $items as $i => $item ) {
    echo $i, $item;
}

Looping over an array (Ruby)

items = ['orange', 'pear', 'banana']

# without indexes
items.each do |item|
    puts item
end

# with indexes
items.each_with_index do |item, i|
    puts i, item
end

Looping over an associative array (PHP)

$continents = array(
    'africa' => 'Africa',
    'europe' => 'Europe',
    'north-america' => 'North America'
);

# without keys
foreach ( $continents as $continent ) {
    echo $continent;
}

# with keys
foreach ( $continents as $slug => $title ) {
    echo $slug, $title;
}

Looping over a hash (Ruby)

continents = {
    'africa' => 'Africa',
    'europe' => 'Europe',
    'north-america' => 'North America'
}

# without keys
continents.each_value do |continent|
    puts continent
end

# with keys
continents.each do |slug, title|
    puts slug, title
end

Important note: Unlike in PHP associative arrays, elements inside a Ruby hash are not ordered.

If you’re having a sense of déjà vu, it’s probably because I wrote a similar post a while ago, but for Python.

To pragmatists the GPL is important as a tool, rather than as an end in itself. Its main value is not as a weapon against `hoarding’, but as a tool for encouraging software sharing and the growth of bazaar-mode development communities. The pragmatist values having good tools and toys more than he dislikes commercialism, and may use high-quality commercial software without ideological discomfort. At the same time, his open-source experience has taught him standards of technical quality that very little closed software can meet.

Eric S. Raymond

On Plugin Support

When I started developing WordPress plugins, most people asking questions in the support forums seemed like hobbyists building sites for themselves. Since then, I’ve noticed two trends that irk me.

Freelancers

Nowadays, there seem to be a lot more people that get paid to build WordPress sites for others. There’s nothing wrong with that, until you ask me to do your work for free.

I’m not talking about the “Hey, this feature doesn’t work.” type of requests; I’m talking about people dumping some code and asking how to make it do a very specific thing that their client requested.

If you are getting paid to do something, you should either already know how to do it, or spend the time needed to learn how to do it, instead of relying on the kindness of suckers strangers.

Commercial software

Commercial themes are booming and paid plugins are also becoming common. Again, there’s nothing wrong with that, but don’t expect much sympathy from me when the premium theme you’re using conflicts with my plugin. I know my code is solid, so why should I spend my free time debugging someone else’s product that they charge money to support?

Post in their support forums; if it turns out there’s an issue with my plugin, they should be competent enough to fix it and send a patch, or at least explain it to you. 1

Whenever money enters the picture, the gift economy goes out the window; you can’t have it both ways.

  1. This would be the part where I suggest you hire me, but I’m currently not taking on WordPress consultancy work. Sorry.