臃肿的构造函数参数


DDD Bloated Constructor Parameter

我尝试创建一个名为Vacancy的相当复杂的域,以下是详细信息:

Vacancy.php

class Vacancy extends AbstractEntity implements AggregateRootInterface {
    private $employer;
    private $title;
    private $employerInformation;
    private $position;
    private $category;
    private $employmentInformation;
    private $hideSalary = false;
    private $requiredPerson = 1;
    private $yearsExp = 0;
    private $location;
    private $benefits;
    private $qualification;
    private $details;
    private $postedOn;
    private $lastPostPackage;
    private $expiredOn;
    private $visible = true;
    public function __construct(
        PackageOnHand $package,
        $title,
        Position $position,
        JobCategory $category,
        $employerInformation,
        EmploymentInformation $employmentInformation,
        City $location,
        $qualification
    ) {
        parent::__construct();
        $this->employer = $package->getEmployer();
        $this->title = $title;
        $this->position = $position;
        $this->category = $category;
        $this->employerInformation = $employerInformation;
        $this->employmentInformation = $employmentInformation;
        $this->location = $location;
        $this->setQualification($qualification);
        $this->benefits = new ArrayCollection();
        $this->details = new ArrayCollection();
    }
    // Bunch of setters, getters and methods I don't even want to mention
}

EmploymentInformation类已经封装了4个必需的参数,这使它成为一个实体(我个人感觉不对)。

可以看到,这个特定领域模型的构造函数被扩展到8个参数,更不用说添加更多参数的可能性了。

问题是,所有这些参数都需要使单个Vacancy进入有效状态。

我在这个问题中读过关于Builder模式的内容,但它建议将Builder类制作成一个嵌套类,这在PHP中是无法完成的。

是否有其他模式可以用来清除构造函数膨胀?

您的类可能有几个问题。

首先,你很可能违反了SRP(单一责任原则)。看这个:http://vimeo.com/43592685

。在构造函数中,传递所有方法工作所需的东西。由于您没有指定任何方法(getter和setter不是我所说的方法),因此我无法判断您是否需要所有这些参数。在DDD中,您的方法应该反映UL(通用语言)。现在它看起来就像一个数据(贫血实体)的容器。

Builder模式可以通过多种方式实现,不需要嵌套类。但是构建器有不同的用途,您不应该在这里使用它。我只会为它建一个工厂。

我还会考虑在这里使用"规范"模式。