Adam
Adam

Reputation: 997

Where to put Doctrine queries that use multiple entities in Symfony2?

I have written quite a large and complicated query that internally uses a UNION to select from multiple tables, then returns an array of mixed type entities.

I know that best practises in Symfony say to always put the queries within the repository classes, but how do I decide which to put it in? There's no parent/child relationship between them, the two entities are completely equal.

Upvotes: 1

Views: 1028

Answers (2)

Kamafeather
Kamafeather

Reputation: 9845

Do not use a repository. Repository is bounded to the context of the specific entity type, and it is supposed to be used as a Collection.

Also

A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. (M.Fowler)

And in your case I assume there is no Object-Relational-Mapping, given that you are using a query with a UNION of tables. I assume that your query will not return an actual Doctrine entity, right?

In that case, the query doesn't belong to the Repository pattern, and I suggest you to have a custom class where to encapsulate the big/complex query PHP+SQL code, e.g.:

namespace App\Query

class MyComplexQuery {

(optionally implementing QueryInterface)

and call it from your Controller or Service, without passing from the Repository.


In case you are defining a custom Doctrine Entity to represent the results of your UNION of entities, then use the repository of such entity.

Upvotes: 0

Flosculus
Flosculus

Reputation: 6946

I usually put them in the repository which I consider the most dependent entity in the context.

For instance, if I had two entities: User and Group.
Many entities might have an owning relationship with group, but you can't expect the Group repository to single handedly provide the methods necessary for every specific dependent to function.

It is the responsibility of the dependent (the owning side) to make the connection and hense provide the functionality.

So a method like getUsersInGroup(Group $group) would belong in the UserRepository.

However, you said there are no direct relationships between your two entities.
In this case, my first comment applies. Use the repository whose entity is more dependent on the other within the context of the query. Whichever entity that one is, depends entirely on you.

Upvotes: 1

Related Questions