A few times I’ve heard people complaining about the fact that CakePHP’s find methods return data as arrays and not as objects. “It’s not OO!”, “I want access to Model methods!”, etc. etc. if you’ve followed cake for a while, you’ve probably heard the same.
It’s a bit of a debate as to why you’d want to have objects vs arrays, but I can tell you that most arguments I’ve read call for some breaking of MVC and often arise due to not really understanding the way CakePHP does certain things. Personally, I have nothing against working with arrays especially if my ultimate goal is to just display some data in the view. You can do a quick search at the google group to get views from both sides of the story, so I won’t repeat them here, but please keep in mind that it’s always a good idea to figure out how to use a framework (any framework) to accomplish what’s needed, rather than how to make it work the way you prefer.
So can you return objects from find methods, instead of arrays? Actually it’s very simple, here’s a little gem of code that was posted at the google group, by gwoo:
[sourcecode language=’php’]
function afterFind($results, $primary = false) {
if($primary == true && !is_object($results)) {
return Set::map($results);
}
}
[/cc]
Just to clarify, this is supposed to be added to your app model, so all of the results returned by your find methods, will be automatically “objectified”.
Obviously you’d probably want to expand on that a little, but even with this simple addition you can easily get access to the much desired objects. Just remember to keep in mind that if you do use this approach, it should not be an excuse to break MVC and other conventions.