Doctrine 2, query inside entities

前端 未结 5 1568
自闭症患者
自闭症患者 2020-12-13 16:51

How do I perform queries in an entity?

namespace Entities\\Members;

/**
 * @Entity(repositoryClass=\"\\Entities\\Member\\MembersRepository\")
 * @Table(name         


        
5条回答
  •  借酒劲吻你
    2020-12-13 16:54

    Generally speaking, you shouldn't do this.

    Entities, as a rule of thumb, should not know about the entitymanager (directly, or via some intermediary object).

    The reason for this is mostly testability, but in my experience, it helps keeps things organized in other ways.

    I'd approach it by designing a service class that handles the lookups for you. Your controller (or whatever) would drive it like this:

    find('Member',$member_id); //get a member, some how.
    $svc = new MemberService($em);
    
    $favoriteCommentaries = $svc->getFavoriteCommentaries($member);
    

    As I hint in the comment, if you decide later that you want to add caching (via memcached, for instance) to avoid frequent lookups, you'd do that somewhere near or in this service class. This keeps your entities nice and simple, and easily testable. Since you inject your entitymanager into the service at construction-time, you can mock that as needed.

    getFavoriteCommentaries() could use various implementations. A trivial one would be to proxy it to Member::getFavoriteCommentaries(), which would actually load everything, and then filter out the "favorite" ones. That probably won't scale particularly well, so you could improve it by using the EM to fetch just the data you need.

提交回复
热议问题