Rails Rumble Follow Up
Dynamically Reducing Object Sizes in PHP
November 19th, 2008
After using jQuery for quite a while I’ve become quite attached to using the power of callbacks when dealing with sets of data. I’ve seen equally and perhaps better abilities in Ruby but of course had been let down in the past by PHP’s lack of abilities as a dynamic language.
Today I faced an issue due to the size of my objects. The problem essentially came down to the fact that for the largest objects such as Contact objects the amount of data passed back to the client when doing AJAX calls was pretty sizeable. I wanted to write a function that given a set of property names all the returning objects would be stripped of all but those properties.
I didn’t want to write a function for each set of properties I’d return, so I wrote a generic function that given an array of property names that was all that would be returned from that object and it was surprisingly easy and I think in the end highly dynamic and useful.
It uses the PHP array_walk() function which I’ve never used before. It’s a lot like the Array.each() methods that many other languages have.
private function GetContacts() {
$filter = RequestQuerystring('filter');
$properties = RequestAll('properties');
if (isset($properties)) {
$properties = explode(',', $properties);
}
if (isset($filter)) {
$contacts = [large_objects]
}
if (isset($contacts) && is_array($properties)) {
array_walk($contacts, 'mod_ajax::FilterObjects', $properties);
}
echo json_encode($contacts);
}
private static function FilterObjects(&$object, $key, $properties) {
foreach (get_object_vars($object) as $k => $v) {
if (!in_array($k, $properties)) {
unset($object->$k);
}
}
}
Basically for this array of large objects on each one we call FilterObjects. That has to be a function or static method which I learned as I went. The object is passed in by reference so that any change made to it is reflected in the original array, and it just goes through the variables (properties) of the object and kills anything that isn’t in the allowable parameter list.
This allows me to trim large objects dynamically for any of my client side calls for data and I think is definitely going to save me time in the future. I remember when I first started using PHP I wrote a function for each object to spit out XML, then I progressed to JSON, now I’ve got a nice filter method.
I still feel like there must be a better way to do things, but quite possibly that would exist in another language.
Matthew Lambie
Matthew Lambie


