“Nerfing” a PHP Object

I was trying to think of something with PHP I could blog about that would be short and sweet. Then I thought of something that a good friend of my taught me: nerfing objects.

The Problem

Many times while working with PHP and bigger frameworks, you’ll have classes that extend classes that extand classes. We have an ORM system that interfaces our Database with PHP classes. This makes accessing and updating information easy for us. So lets say we have a class called “Post” that stores a blog post. Our ORM class just takes a few lines of code to hook up our “Post” class to the “posts” database tables. We just extend our base DataObject, which contains all sorts of references to other class isntances. Long story short, this PHP code is awesome, but there is one issue.

Lets say I have an AJAX call that gets some post data, so I want to pass my “Post” class through a JSON parser to send back a JSON version of the PHP class. The problem was that the JSON parser was picking up on the extended classes’s private members and such, so it was spitting back a whole lot of stuff we didn’t want it to that belonged to the ORM classes.

The Solution

So what do we do? We “nerf” the class. Nerfing is a term used by gamers about video games. It means “[to make] a change to a game that reduces the desirability or effectiveness of a particular game element. The term is also used as a verb for the act of making such a change. The term is used as a reference to the NERF brand of toys which are soft and less likely to cause serious injury.” (Wikipedia)

So we make a “Nerfed” version of the class, with no functions, or extended protected members, just the data. We do this by using two parts of PHP:

  • stdClass PHP Class
  • PHP’s Reflection Class

Just attach this function to your class and you’ll be able to “nerf” it.

[php]

dbFields;

foreach ($dbFields as $n => $v)
{
$nerf->$n = $v;
}
//var_dump($nerf);

$me_ref = new ReflectionClass(get_class($this));
$me_properties = $me_ref->getProperties();
foreach($me_properties as $m)
{
if($m->isPublic())
{
$name = $m->getName();
$nerf->$name = $this->$name;
}
}

return $nerf;
}

}

?>

[/php]

Hopefully that makes sense, but the Reflection capabilities of PHP are pretty simple and powerful. Hopefully over the next few weeks I’ll be posting some more tricks with PHP Reflection.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close