php - Encapsulate instantiation arguments or make them explicit? -
my question regarding instantiation options...
(i've written in php, question applicable general oop)
take example domain object:
class user{ private $id; private $name; private $email; ... etc }
it instantiated in 2 places.
controller: request comes in client side. controller extracts post variables, instantiates user object , passes down stack.
data access layer: getuser() method called service. user data pulled db, , dal instantiates user object , passed stack.
we have 2 options constructor
option 1
public function __construct($id, $name, $email,...){ $this->id = $id; $this->name = $name; $this->email = $email; ... }
in case controller instantiates object so:
parse_str($_post['data'], $data); $user = new user($data['id'], $data['name'], $data['email'],...);
and dal instantiates object so:
$row = ...get row db... $user = new user($row['id'], $row['name'], $row['email'],...);
which clear / explicit, couples our domain object's instantiation controller , dal. if decide add field user table, have update domain object, controller , dal.
option 2
public function __construct($data){ ...check $data valid etc, handle if not... $this->id = $data['id']; $this->name = $data['name']; $this->email = $data['email']; ... }
in case controller instantiates object so:
parse_str($_post['data'], $data); $user = new user($data);
and dal instantiates object so:
$row = ...get row db... $user = new user($row);
now if decide add field user table, have update domain object.
questions
- what advantages of each of these constructor options?
- is there best practices way of doing this?
Comments
Post a Comment