Search code examples
phpsymfonymodel-view-controllerdbal

Repositories reeplacement in a Symfony project configured with DBAL


I'm working in a project in Symfony 3.0.1 that use five databases with DBAL as data access layer. I always worked in Symfony with ORM and I always used the next MVC model:

Data access:

CONTROLLER -> REPOSITORY (the queries goes here) -> ENTITY

Display results:

CONTROLLER -> render($view,$params) -> VIEW

This model allow short and simple controllers, but now I'm using DBAL so I can't use repositories.

The question is:

How can I achieve a similar model by using DBAL? In others words, Where should I put the queries?

Should I use services instead of repositories?

Note: I only use the select statement in that databases.

Thanks in advance!


Solution

  • You don't need an ORM in order to use entities.
    Likewise, you do not need Doctrine to be able to build repositories once a repository is a implementation of design pattern:

    Repository

    Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects. Read more

    Even though you can't use Doctrine ORM you still can to design POPO classes against an abstract model class or/and model interface.
    You could inject DBAL Connection object for each model/entity via construct or setter method. After creating repo classes is easy. Returning collection objects, hydrating items or using raw arrays is up to you.

    Edit #1

    I have added a real worl exemple I have used in the past (few years ago), look:

    https://github.com/felipsmartins/misc-and-code-snippets/tree/master/php/model-exemple/src/AppBundle/Model

    Edit #2

    Regarding services, it would much better if there is specialized and well defined models (as opposed to Anemic Models) working together inside a service which coordinates the whole transaction, in this case it would be what we know by Unit of Work (see Unit of Work Pattern)