Reputation: 20590
I'm confused on what a constructor looks like in PHP using a DDD aproach. This is what I have so far:
Entity
class People {
// Fields
private $id;
private $first_name; // required
private $middle_name;
private $last_name; // required
private $phone; // required (or mobile_phone required)
private $mobile_phone;
private $email; // required
private $alt_email;
private $something_else; // required
public function __construct($fields){
// Set some properties
$this->setFromArray($fields);
// Don't instantiate a new entity object in an invalid state
// (ie. determines if required fields are given)
if(!$this->isValid()){
throw new Exception("Can't create person");
}
}
// some getters and setters...
// some other domain methods so entity is not anemic
...
Repository
class PeopleRepository { // <-- Should probably be an interface
public function get($id){
...
}
public function save(People $people){
// Will INSERT or UPDATE based on if an ID is set in $people
}
Simple Example
// a very very simple example
$peopleRepo = new PeopleRepository();
$people = new People($_POST);
$peopleRepo->save($people);
I don't want to use any ORM. Is the way I do it above a correct approach for an entity constructor in DDD? Please explain and give example in PHP of how entity constructors look in DDD (I'm having a hard time finding good examples).
Upvotes: 2
Views: 1776
Reputation: 2595
Passing array of values on the constructor is not a good idea. If the required data is not present in the array. your domain entity will be in invalid state.
Just put the required fields individually on the constructor, that way it is more readable and the required fields are explicit. If you forgot to provide the required data, you will have an error which is supported by most good IDEs.
__construct($firstName, $lastName, $phone, $email) { }
You might want also to consider using ValueObject to group related data to narrow down your constructor. For more information about ValueObjects follow this links.
http://richardmiller.co.uk/2014/11/06/value-objects/
In your case with name. encapsulate them inside ValueObject FullName
final class FullName
{
private $firstName;
private $middleName;
private $lastName;
public function __construct($firstName, $lastName, $middleName = null)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->middleName = $middleName;
}
// getters method ONLY
// you need to instantiate new FullName if you want to change the fields
}
then you can pass it to the constructor of People
__construct(FullName $fullName, $phone, $email) { }
If you really have huge constructor, you might consider builder pattern.
How many constructor arguments is too many?
Upvotes: 3