29th Jun 2008

Upon Reflection

The other day I was revising the one of the systems on one of the sites I work on into an object oriented structure. Everything was all well and good until I realized that I had to pass the values contained in one of my new objects into the templating system that we use. So I initially just passed a reference to the object. This did not work out so well.

It turns out that the templating system was having a hard time dealing with instance variables that are references to other objects and decided to throw a fit and halt processing. So I started looking for an easy way to translate my object into something the templating system could use (an array). More specifically, I wanted to produce an array that contained the values of my instance variables, but only the ones that were not references to other objects.

I decided to add a method called toArray to the object in question. Now I just needed an implementation. My first shot at this was to use PHP’s get_object_vars passing $this as a parameter.

public function toArray(){
return get_object_vars($this);
}

However, all was not well. It seems that when you call this function passing $this as a parameter it returned all of the variables from all of the objects referenced in instance variables. So I was basically back were I started.

So I gave it a bit of thought and came up with this.

/**

* Convert values held in instance variables into an array.
* This allows the data to be more easily used by a
* smarty variableĀ  as well as making the data more easily cachable.
*
* @return Array
*/
public function toArray ()
{
$data = array();
foreach ( $this as $key => $var )
{
/**
* Exclude complex objects from the array.
*/
if ( !get_class( $var ) )
{
$data[$key] = $var;
}
}
return $data;
}

Problem solved. Now I only got back an array that contained the values of instance variables for that specific class that were not references to other objects.

Comments are closed.