I was wondering which way is better to work with.
Using private attributes at a controller class, or using only one private attribute as an array of attributes.
Instead of:
class User{
private $id;
private $firstName;
private $surname;
private $age;
private $gender;
private $city;
...
...
}
class User{
private $data;
}
and then be able to do something like this:
function __construct(){
//this would contain id, firstName, username, age, gender...
$data = $model->getData();
}
Thanks
Using arrays you will loose any autocompletion tools while writing code on your class. You will loose the ability to detect syntax errors on your attributes. You will in fact make your code more confuse, less descriptive.
Using objects is usually a good thing to allow for a better maintainability, for things that will be shared with several developers, or with yourself several months or years after you’ve been writing it. In my opinion you should stay with attributes. A more confuse code may be ‘optimised, or shorter to read, but if you want that just write assembly code. If you want to make object code, do it in a clean way, you will always find a situation where it will save your future life.
Your problem here is that you maybe think it’s a real pain to maitain a clean mapping between your object attributes and the Model layers columns. But whatever you try, this is the minimum thing you will always have to code in all your application, if it’s not done here you will still have to know these attributes when using your object. Chances are that this is a Pattern of Failure:
With your DataModel loading example I can see for example two potential future problems:
In fact if you want to make something filling the object attributes based on the object related model you should really think it a something more general, maybe implying other objects, interfaces, factories, several methods. And at least not in the construct.
Use array for arrays, and attributes for attributes, let the PHP engine optimize attributes management, I’m sure code optimizer will make better things with attributes than with arrays indexed by strings.