开发者

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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜