My question is regarding instantiation options...
(I've written in PHP, but the question is applicable to general OOP)
Take an example domain object:
class User{
private $id;
private $name;
private $email;
...
etc
}
It is currently instantiated in 2 places.
Controller: A request comes in from client side. The controller extracts the POST variables, instantiates the User object and passes it down the stack.
Data Access Layer: Some getUser() method is called from some service. The user data is pulled from the DB, and the DAL instantiates the User object and passed it up the stack.
We have 2 options for the constructor
Option 1
public function __construct($id, $name, $email,...){
$this->id = $id;
$this->name = $name;
$this->email = $email;
...
}
In this case the controller instantiates the object like so:
parse_str($_POST['data'], $data);
$user = new User($data['id'], $data['name'], $data['email'],...);
And the DAL instantiates the object like so:
$row = ...Get row from DB...
$user = new User($row['id'], $row['name'], $row['email'],...);
Which is clear / explicit, but couples our domain object's instantiation to the controller and the DAL. If we decide to add another field to the User table, we have to update the domain object, the controller and the DAL.
Option 2
public function __construct($data){
...check $data is valid etc, handle if not...
$this->id = $data['id'];
$this->name = $data['name'];
$this->email = $data['email'];
...
}
In this case the controller instantiates the object like so:
parse_str($_POST['data'], $data);
$user = new User($data);
And the DAL instantiates the object like so:
$row = ...Get row from DB...
$user = new User($row);
Now if we decide to add another field to the User table, we only have to update the domain object.
Questions
- What are the advantages of each of these constructor options?
- Is there a best practices way of doing this?