jonathancardoso
jonathancardoso

Reputation: 12717

Repositories should always return objects?

This question got me today, my repositories should always return full objects? They can not return partial data (in an array for example)?

For example, I have the method getUserFriends(User $user) inside my repository Friends, in this method I execute the following DQL:

$dql = 'SELECT userFriend FROM Entities\User\Friend f JOIN f.friend userFriend WHERE f.user = ?0';

But this way I'm returning the users entities, containing all the properties, the generated SQL is a SELECT of all fields from the User table. But let's say I just need the id and the name of the user friends, there would be more interesting (and quick) get just these values?

$dql = 'SELECT userFriend.id, userFriend.name FROM Entities\User\Friend f JOIN f.friend userFriend WHERE f.user = ?0';

These methods are executed in my service class.

Upvotes: 0

Views: 398

Answers (2)

Maxence
Maxence

Reputation: 13296

You can use partial keyword in your DQL : http://www.doctrine-project.org/docs/orm/2.0/en/reference/partial-objects.html?highlight=partial

But only do that if your app has performance issues.

Upvotes: 1

Benjamin Dubois
Benjamin Dubois

Reputation: 961

From a database perspective, performance will not be that much affected by the number of fields, unless the number of rows to return is really huge (millions of rows, probably) : the hardest part for the db is to make the joints, and build the resultset from the tables.

From a php perspective, that depends on multiple factors, like the complexity and the number of objects created.

I would take the problem differently : I would profile and stress-test my code in order to see if performance is an issue or not, and decide to refactor only if needed (switching from doctrine to a hand-made model is time consuming, will the performance gain be worth it ?)

EDIT : and to answer your initial question : fetching complete objects will lead to easier caching if needed, and better data encapsulation. I would keep these until they represent a big performance issue.

Upvotes: 1

Related Questions