jeudi 20 décembre 2018

Using query builders as data mapper layer

Can you use a query builder like (Doctrine DBAL, Aura.SqlQuery, etc) as your data mapper layer or do you need to abstract it further? E.g.,

Sample A

<?php

class PersonsRepository
{
    private $queryBuilder;

    public function __construct(QueryBuilder $queryBuilder)
    {
        $this->queryBuilder = $queryBuilder;
    }

    public function getName($id)
    {
        $row = $this->queryBuilder
                    ->select('persons')
                    ->where('id', $id);

        return $row['name'];                
    }
}

// example usage

$pdo = new PDO('...');
$repo = new PersonsRepository(
            new QueryBuilder($pdo));

Is that already ok or do you need to abstract it further like this:

Sample B

class PersonsRepository
{
    private $mapper;

    public function __construct($mapper)
    {
        $this->mapper = $mapper;
    }

    public function getName($id)
    {
        $row = $this->mapper->find([            
            'id' => $id
        ]);

        return $row['name'];                
    }
}

class PersonMapper
{
    private $queryBuilder;

    public function __construct(QueryBuilder $queryBuilder)
    {
        $this->queryBuilder = $queryBuilder;
    }

    public function find($id)
    {
        $row = $this->queryBuilder
                    ->select('persons')
                    ->where('id', $id);

        return $row;
    }
}

$pdo = new PDO('...');
$repo = new PersonsRepository(
            new PersonMapper(
                new QueryBuilder($pdo)));

If we go with the definition of data mapper

A layer of Mappers (473) that moves data between objects and a database while keeping them independent of each other and the mapper itself.

In essence, a query builder is a layer in between the repo and the db. That said, is Sample A considered to be using a data mapper already or does it have to be explicit, like Sample B?

Aucun commentaire:

Enregistrer un commentaire