php中DDD的实体构造函数是什么样的?

时间:2015-04-28 22:55:35

标签: php constructor entity domain-driven-design ddd-repositories

我对PHP中使用DDD aproach的构造函数看起来很困惑。这就是我到目前为止所做的:

实体

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
    ...

存储库

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
    }

简单示例

// a very very simple example
$peopleRepo = new PeopleRepository();
$people = new People($_POST);
$peopleRepo->save($people);

我不想使用任何ORM。对于DDD中的实体构造函数,我的方法是否正确?请在PHP中解释并举例说明实体构造函数在DDD中的外观(我很难找到好的例子)。

1 个答案:

答案 0 :(得分:2)

在构造函数上传递值数组并不是一个好主意。如果阵列中不存在所需数据。您的域名实体将处于无效状态。

只需将所需的字段单独放在构造函数上,这样它就更具可读性,并且必需的字段是显式的。如果您忘记提供所需的数据,则会出现大多数优秀IDE支持的错误。

__construct($firstName, $lastName, $phone, $email) { }

您可能还需要考虑使用ValueObject对相关数据进行分组以缩小构造函数的范围。有关ValueObjects的更多信息,请点击此链接。

http://richardmiller.co.uk/2014/11/06/value-objects/

在您的案件中有姓名。将它们封装在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
}

然后你可以将它传递给People

的构造函数
__construct(FullName $fullName, $phone, $email) { }

如果你真的有庞大的构造函数,你可以考虑构建器模式。

How many constructor arguments is too many?