Sunday, June 22, 2008

array to object

So I really get sick of:

if($promotion['req']['min'] > 10)

I love using multidimensional arrays for partitioning data/namespaces for the sake of sanity but the access is really quite.. icky. So I came up with a quick hack to turn a multidimensional array into an object so the above could be more like:

if($promotion->req->min > 10)

It saves a few characters and I think it becomes a LOT more readable as well as easier to comprehend especially on an oo level.

The code is simple/hackish:

class oArray{
/*class to turn a keyed array to object
IF a key is numeric it will be prepended with a letter n i.e. key 2 becomes n2
Really though this is meant for meaningful key=>val relationships
*/
function __construct($array){
foreach($array as $key=>$val){
$key = is_numeric($key) ? 'n'.$key : $key;
$this->$key = is_array($val) ? new oArray($val) : $val;
}
}
}
function oArray($array){
return new oArray($array);
}

You will notice that I have a function called oArray as well as a class which merely wraps the whole "$var = new object(params)" deal as that gets pretty repetitive. So Now I can do:

//instantiation
$promotion = oArray(Array(
'req'=>Array(
'min'=>50,
'max'=>100),
'grants'=>Array(
'limit'=>50,
'type'=>504))));

//access
if($promotion->req->min <= $promotion->grants->limit);
v.s.
if($promotion['req']['min'] <= $promotion['grants']['limit']);

This was all blatantly inspired by the way you can access objects in emcascript. I know that this is really a total abuse of php and oo design but when you are working with legacy systems sometimes you'll do anything to interject some semblance of sanity. Also I was listening to john zerzan lectures whilst I composed this. Maybe that explains why I would so something so meaningless; almost in opposition to his stance on technology.

No comments: