Is configuration with arrays a bad smell?

Share this article

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->addFavColor('red');
$person->addFavColor('blue');
$person->addFavColor('green');
$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.

Harry FuecksHarry Fuecks
View Author

Harry Fuecks is the Engineering Project Lead at Tamedia and formerly the Head of Engineering at Squirro. He is a data-driven facilitator, leader, coach and specializes in line management, hiring software engineers, analytics, mobile, and marketing. Harry also enjoys writing and you can read his articles on SitePoint and Medium.

Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form