Blog Post RSS ?

Blogs » PHP » Is configuration with arrays a bad smell?
 

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->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.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Ping.fm
  • Twitthis

Related posts:

  1. Warning: 6 Signs You Are About To Hire A Bad Designer Or Developer As a companion to the post about warning signs for...
  2. Why Opera 10’s User Agent Smells Bad The user agent in the soon-to-be-released Opera 10 will report...
  3. Are PHP Namespaces Really So Bad? Namespaces have caused a divide amongst developers who either love...
  4. What’s So Bad About CSS Frameworks? Standards-aware web developers often feel conflicted about using CSS frameworks....
  5. Cross-browser JSON Serialization in JavaScript JSON serialization can be incredibly useful, but few browsers support...

This post has 5 responses so far

Sponsored Links

SitePoint Marketplace

Buy and sell Websites, templates, domain names, hosting, graphics and more.

Follow SitePoint on...