简体   繁体   English

数据映射器-我应该使用依赖注入吗?

[英]Data Mapper - should I use dependency injection?

Should I pass model as an dependency injection in data mapper pattern or should I declare the model inside the mapper class? 我应该将模型作为数据映射器模式中的依赖项注入传递,还是应该在映射器类中声明模型?

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;
    }
}

or: 要么:

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;
    }
}

Which one is correct? 哪一个是正确的?

The mapper should create objects, be it by itself or using a factory. 映射器应该创建对象,无论是单独创建还是使用工厂。 Injecting an "empty" object and then always return the same object but with different data does not make much sense. 注入一个“空”对象,然后总是返回相同的对象,但使用不同的数据没有多大意义。

Should you inject a factory? 你应该注入工厂吗? It's a good idea to separate object creation and object usage. 分离对象创建和对象用法是个好主意。 But IMHO the data mapper falls into the object creation category itself, so $model = new Model fits perfectly fine. 但是恕我直言,数据映射器本身属于对象创建类别,因此$model = new Model非常合适。

Another remark: In your first example, you would inject the model with invalid state, ie uninitialized. 另一个说明:在第一个示例中,您将为模型注入无效状态,即未初始化。 Allowing invalid state can lead to bugs and is good to avoid. 允许无效状态会导致错误,因此可以避免。

Actually you allow invalid state in your second example as well, at least theoretically. 实际上,至少在理论上,您也可以在第二个示例中允许无效状态。 I'd recommend passing the required data via constructor instead of setter to make sure, instances of Model are always valid. 我建议通过构造函数而不是setter传递所需的数据,以确保Model实例始终有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM