我应该在数据映射器模式中将模型作为依赖项注入传递,还是应该在映射器类中声明模型?
class Mapper
{
public function __construct(
$model
)
{
$this->model = $model;
}
public function mapObject(array $row)
{
$this->model->setArticleId($row['article_id']) ;
$this->model->setTitle($row['title']);
$this->model->setDescription($row['description']);
$this->model->setContent(isset($row['content']) ? $row['content'] : null);
$this->model->setTemplate(isset($row['template']) ? $row['template']['path'] : null);
return $this->model;
}
}
或:
class Mapper
{
public function mapObject(array $row)
{
$model = new Model;
$model->setArticleId($row['article_id']) ;
$model->setTitle($row['title']);
$model->setDescription($row['description']);
$model->setContent(isset($row['content']) ? $row['content'] : null);
$model->setTemplate(isset($row['template']) ? $row['template']['path'] : null);
return $model;
}
}
哪一个是正确的?
映射器应该创建对象,无论是自己创建还是使用工厂创建。注入一个"空"对象,然后总是返回相同的对象,但使用不同的数据,这没有多大意义。
你应该注入一个工厂吗?将对象创建和对象使用分开是个好主意。但是IMHO数据映射器本身属于对象创建类别,因此$model = new Model
非常适合。
另一句话:在你的第一个例子中,你会给模型注入无效状态,即未初始化。允许无效状态可能会导致错误,最好避免。
事实上,在第二个例子中,你也允许无效状态,至少在理论上是这样。我建议通过构造函数而不是setter传递所需的数据,以确保Model
的实例始终有效。