Run
Run

Reputation: 57196

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?

Upvotes: 1

Views: 337

Answers (1)

Fabian Schmengler
Fabian Schmengler

Reputation: 24551

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.

Another remark: In your first example, you would inject the model with invalid state, i.e. 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.

Upvotes: 1

Related Questions