By Harry Fuecks

Is configuration with arrays a bad smell?

By Harry Fuecks

Something I see fairly often in PHP, where OOP / classes are concerned;

$options = array (
'name' => 'Harry Fuecks',
'favoritecolors' => array ('red','green','blue'),
'favoritefoods' => array (
'breakfast' => 'English Breakfast',
'lunch' => 'Steak and chips',
'dinner' => 'Tandori Chicken',
'etcetc' => 'aarrrgh!'

$person = new Person($options);

In other words a giant array used to “configure” the runtime behaviour of an object.

For me this is a bad smell. For a start it usually means there’s some giant class method in there somewhere which deals with “parsing” the array and reacting accordingly. More importantly, think it’s a nightmare for the user – arrays are hard to document and easy to get wrong when you’re hand-coding one.

I’d much rather see something like;

$person = new Person();
$person->name('Harry Fuecks');
$person->addFavFood('breakfast','English Breakfast');
$person->addFavFood('lunch','Steak and Chips');
$person->addFavFood('dinner','Tandori Chicken');

The methods are easy to document (with phpDocumentor) and, IMO, it’s alot easier to test / use. The API makes what’s happening explicit.

Otherwise, wise use of parse_ini_file(). PHP can parse an ini file into variables faster than it can parse and execute an equivalent PHP script….

Rant over.

The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account