【问题标题】:Communication through events between an entity and its repository in Doctrine2在 Doctrine2 中通过实体与其存储库之间的事件进行通信
【发布时间】:2011-10-24 09:20:34
【问题描述】:

我开始在具有“组”实体的项目中使用 Doctrine 2,该实体可以从另一个组继承,具有以下架构:id | parent_id | name

因为层次结构可以更深,我使用链接表“group_group”,使用此架构:ancestor_id | descendant_id | depth

这个想法是任何组都链接到它的所有祖先和后代,depth 字段表示关系的距离,这样我就不必使用许多 SQL 请求遍历父母或孩子,一个人可以得到所有的结果。 我尝试使用 Doctrine 的 ManyToMany 关系,但无法通过 depth 字段对其进行排序,因此我使用实体的存储库来获取相关的祖先和后代。

由于实体无法访问其存储库,我想知道是否有办法让实体分派其存储库可以侦听的事件,以便当实体尝试访问其祖先/后代时,仓库可以响应吗?

感谢您的帮助。

【问题讨论】:

    标签: events entity doctrine-orm


    【解决方案1】:

    Entity 不应具体引用Repository,但定义Interface 并让您的Repository 实现此接口并将其注入Entity 并没有任何问题。

    类似于这个解决方案Doctine 2 Restricting Associations with DQL

    interface TreeInterface
    {
       public function findParent();
       public function findChildren();
    }
    

    然后是你的实体。

    class Group
    {
        $repository;
    
        setRepository(TreeInterface $repository)
        {
            $this->tree = $repository;
        }
    
        public function getParent()
        {
            return $this->repository->findParent($this);
        }
    
        public function getChildren()
        {
             return $this->repository->findChildren($this);
        }
    }
    
    class GroupRepository extends EntityRepository implements TreeInterface
    {
        public function findParent(Group $group)
        {
            return //stuff
        }
    
        public function findChildren(Group $group)
        {
            return //stuff
        }
    }
    

    而你就是这样使用它的。

    $group = $em->find('Group', 1);
    $group->setRepository($em->getRepository('Group'));
    $children = $group->getChildren();
    

    为了避免每次获得孩子时都设置存储库,我会查看 EventManager 和 postLoad 事件,看看是否可以在加载时将 TreeInterface 注入到实体中。

    【讨论】:

      猜你喜欢
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 2016-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多