如果这些实体需要构造参数,如何将实体依赖注入到存储库中?

How to do Dependency Injection of entities into a repository if those entities have required arguments for construction?

如果这些实体需要构造参数,我该如何将实体依赖注入到存储库中?

举这个简单的例子(在 PHP 中,但问题与语言无关):

个人实体

class Person
{
    private $firstName = "";
    private $middleName = "";
    private $lastName = "";
    private $dateOfBirth;
    private $dateOfDeath;

    public function __construct($firstName, $middleName = "", $lastName)
    {
        $this->firstName = $firstName;
        $this->middleName = $middleName;
        $this->lastName = $lastName;

        // Validation
        if(empty($this->firstName) || empty($this->lastName){
            throw new Exception("first and last name required");
        }
    }

    // ...
}

人物资料库

class PersonRepository
{
    public function __construct(Person $person)  // <-- problem, need required arguments
    {
         $this->person = $person;
    }

    public function fetchById($id)
    {
         // Query database
         // ...

         // Hydrate and return a person object
         // ...

         return $person;
    }

    // ...
}

那我错过了什么?注入实体并避免在存储库中使用 new 运算符的标准方法是什么?

了解 "Abstract Factory"。是一种模式。

class PersonRepository
{
    public function __construct(PersonFactory $factory){
         $this->personFactory = $factory;
    }

    public function getById($id)
    {
         // ...
         return $this->personFactory->create($row['name'], $row['surname'], ...);
    }
}