【发布时间】:2014-07-03 10:39:31
【问题描述】:
我尝试创建一个名为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 进入其有效状态。
我在this SO question读到了Builder Pattern,但是它建议Builder类在里面做成一个嵌套类,这在PHP中是做不到的。
还有其他模式可以用来清除构造函数膨胀吗?
【问题讨论】:
-
与其在上面的代码中的类中做一个嵌套类,不如只做一个完全独立的类,由类构造函数所需的参数组成,并传入新的实例已创建,将班级班级划分为空缺班级?
-
@Kritner 你能举个例子吗?
-
好吧,从原始问题的链接中,它显示了嵌套类,您可以将其拉出到它自己的类中,而不是将其嵌套在一个类中。现在我想到了,但我认为它不会解决您的问题,它只会将构造函数膨胀重定向到不同的类。如果您的所有参数仍然需要,您可能仍希望通过我认为的构造函数来设置它们。
-
我在想他可以只传入一个数组,然后让构造函数立即调用一个私有的
setFromArray方法来设置所有属性。然后构造函数调用isValid方法以确保设置所需的属性。这样他的属性保持私有,他只需要传递 1 个参数(一个可能有效/无效的数组),如果无效,构造函数将抛出异常/错误(确保实体未在无效状态下实例化) .
标签: php oop design-patterns domain-driven-design