Cut down on temporary variables in PHP with Fluidics

Posted on March 14th, 2008 by Luke Visinoni

Ollie Saunders, a colleague of mine and a regular at the DevNetwork forums has put together a very slick little set of functions he has collectively termed “PHP Fluidics”. If there is one thing that really sucks about PHP, it’s how often you have to use temporary variables to get to methods or array elements you need. Fluidics makes this process (and several others) much easier. We use this library in just about everything we code these days and I’d like to point out a few reasons why.

One common example is when you need to instantiate an object and call a method on it. Normally, you’d have to do something like the following.

$person = new MC2_Person(23);
$person->getFullName();

While this isn’t all that painful when you only need to do it once, in even a moderate sized project, you’ll need to do something like this hundreds of times. Now let’s look at the fluidics way to do this.

with(new MC2_person(23))->getFullName();

Another extremely useful function in fluidics is the dindex function. After using python for the last few months I have really grown fond of the built-in dictionary method get(). What it does is allow you to request an index on an array (called a dictionary in python) and if it doesn’t exist, you can provide a default. In python the syntax is like dict.get(’key’, ‘defaultval’). In fluidics it’s like this:

$lunch = array('snack' => 'cheetos', 'drink' => 'mountain dew');
$drink = dindex($lunch, "drink", "pepsi"); // returns "mountain dew"
$sandwich = dindex($lunch, "sandwich", "ham"); // returns "ham"

I could sit here and list all the functions that make this little library so useful, but Ollie does a better job of it anyway, so check out his googlecode project. I hope you like it as much as I did.

Read more about fluidics here.
Ollie Saunders’ Blog

Leave a Reply