我正在创建自己的 MVC 框架,只是为了学习一些新东西,最近遇到了这个问题。可以说我有这样的:
Class Post extends \application\BaseClass
{
private $objPostDetail = null;
private $objAuthor = null
private $objCategory = null;
private $objType = null;
private $objTitlePicture = null;
public function __construct(PostDetail $objPostDetail,
Author $objAuthor,
Category $objCategory,
Type $objType,
TitlePicture $objTitlePicture)
{
$this->objPostDetail = $objPostDetail;
$this->objAuthor = $objAuthor;
$this->objCategory = $objCategory;
$this->objType = $objType;
$this->objTitlePicture = $objTitlePicture;
}
}
然后构造函数中使用的一些对象也可以复杂地创建。我从 PostDAO 类中获取数据,该类返回数据数组。现在的问题是如何创建这个类的新实例,因为它可能在应用程序的许多地方。我认为到处创建 $objAuthor,然后 $objCategory 等最终创建 $objPost 并不好。所以我创建了我认为可能被称为工厂的东西:
Class PostFactory extends \application\BaseFactory
{
private $arrData = null;
private $objPostDetail = null;
private $objCategory = null;
private $objType = null;
private $objTitlePicture = null;
public function __construct($arrData)
{
$this->arrData = $arrData;
}
public function build()
{
$this->objPostDetail = $this->buildPostDetail();
$this->objCategory = $this->buildCategory();
$this->objType = $this->buildType();
$this->objTitlePicture = $this->buildTitlePicture();
return $this->buildPost();
}
private function buildPostDetail()
{
$objPostDetail = new \includes\classes\factories\PostDetailFactory($this->arrData);
return $objPostDetail->build();
}
private function buildCategory()
{
$objCategory = new \includes\classes\factories\CategoryFactory($this->arrData);
return $objCategory->build();
}
private function buildType()
{
$objType = new \includes\classes\factories\TypeFactory($this->arrData);
return $objType->build();
}
private function buildTitlePicture()
{
$objTitlePicture = new \includes\classes\factories\TitlePictureFactory($this->arrData);
return $objTitlePicture->build();
}
private function buildPost()
{
return new \includes\classes\Post($this->objPostDetail, $this->objCategory,
$this->objType, $this->objTitlePicture);
}
}
它工作得很好,但我不喜欢我有两倍多的类,而且我不知道实例化 Post 需要什么参数,因为我将数组传递给 Factory 类(因为我想避免构造函数中的许多参数)。所以,我的问题是如何创建这样的类实例的最佳方法是什么?
提前感谢您的帮助。