When returning large amounts of data, it can be common to turn to a built-in PHP data structure: the array. But in object-oriented code, arrays make poor object-to-object data transfer mechanisms. Object-oriented programming is and should be focused on objects. That means that each array should be converted into an object, and collections too.
The reason is simple: when one object makes a request to another object, it should generally get back an object unless the response is scalar. For example, asking for a data set from the database ought to generate an object, not an associative array of data.
Using objects allows for type hinting and type evaluation, not to mention creates additional type safety for your application. Arrays can be changed, and have no methods; objects can be made immutable, and can have methods that access bits of data. Naked arrays form excellent value objects that can be hinted on, ensuring the fidelity of the data in the future.
Of course, returning an object or a collection can have some unintended side effects. For starters, you can’t return a malformed value object, so you’ll need to throw more exceptions when the object can’t be created due to some error. That will mean additional error handling for specific error conditions in the calling object.
When returning a collection of value objects, you’ll want to make sure the data is homogeneous – that is, the value objects are all of the same type. Otherwise, returning an array is perfectly valid. Collections should only contain objects of a single type.
You should also consider returning an array if the call is solely internal (between protected methods, for example); value objects should be used for external calls, but arrays are perfectly suitable for internal calls.
Finally, when it comes to defining your return values, use exceptions to denote errors, and only return when you have a fully formed object or collection to return. This will help improve your application’s error handling, and make explicit the conditions by which failure occurs. In addition, by having a single, consistent return value, you can know that when you get a response, the request you made was successful.
Value objects are extremely powerful, and should be used regularly. What are your favorite places to replace arrays with value objects?
Frustrated with your company’s development practices?
You don't have to be!
No matter what the issues are, they can be fixed. You can begin to shed light on these issues with my handy checklist.
Plus, I'll help you with strategies to approach the issues at the organization level and "punch above your weight."