【问题标题】:Same function in several Entity Repositories without Base Repository?没有基本存储库的多个实体存储库中的相同功能?
【发布时间】:2015-11-06 17:59:05
【问题描述】:

假设我在 Doctrine 中有一组实体,每个实体都有一个自定义存储库。

对于其中许多实体,我有一个扩展链,假设 MyEntity extends GenericEntity extends StandardEntity extends BaseEntity 并且存储库遵循相同的方法。

就我而言,这是完全有效的,因为根据 OOP,MyEntity 只是通用基类的一个非常具体的版本。

现在我有一个这样的存储库功能:

    public function getCount()
{
    $qb = $this->_em->createQueryBuilder();
    $qb->select('COUNT(me)');
    $qb->from('MyEntity', 'me');

    return $qb->getQuery()->getSingleScalarResult();

}

为多个实体提供相同的功能会很棒,我不会避免代码重复。

我的理解选项:

  1. 接口 iCountableRepository:仅部分有用,因为我需要在课堂上实现。
  2. 扩展 CountEntityRepository:不适合我的扩展链,在 PHP 中也无法实现多重继承
  3. 特征 CountableRepository:

这听起来对我来说是最有用的方法。但是是否有可能并建议有类似的东西:

    public function getCount()
    {
    $qb = $this->_em->createQueryBuilder();
    $qb->select('COUNT(me)');
    $qb->from($this->_entityName, 'me');

    return $qb->getQuery()->getSingleScalarResult();

    }

在特质中是否可能出现“这”?

或者还有什么方法可以构建可以“注入”到某些选定存储库中的通用存储库函数?

【问题讨论】:

标签: symfony doctrine-orm


【解决方案1】:

特征对于这样的事情是完全可以的。 但您也可以扩展基本存储库。我真的不明白为什么这是不可能的。我认为你应该能够做到这一点:

<?php
namespace Application\Repository;

use Countable;

class BaseEntityRepository extends EntityRepository implements Countable
{
    /**
     * Count items in this repository
     *
     * @return int
     */
    public function count()
    {
        $qb = $this->createQueryBuilder('b');
        $qb->select('COUNT(b)');
        return $qb->getQuery()->getSingleScalarResult();
    }
}

然后:

<?php
namespace Application\Repository;

class StandardEntityRepository extends BaseEntityRepository
{

}

然后:

<?php
namespace Application\Repository;

class GenericEntityRepository extends StandardEntityRepository
{

}

还有:

<?php
namespace Application\Repository;

class MyEntity extends GenericEntityRepository
{

}

【讨论】:

  • 谢谢,我同意 - 显然我的问题并不完全清楚。这种方法当然在这里有效,但是如果 MyEntityA 从 GenericA/StandardA 扩展而 MyEntityB 从 GenericB 扩展等等怎么办。所以如果没有共同的根元素。但是当一个特质很好时,你已经帮助了我!非常感谢!
  • @LBA 您的实体类不相互扩展并不意味着您不能使用相同的基础存储库类。但是一个特质可能会更好......
猜你喜欢
  • 1970-01-01
  • 2018-07-18
  • 2019-04-17
  • 1970-01-01
  • 2020-02-06
  • 1970-01-01
  • 2023-02-09
  • 2016-07-06
  • 1970-01-01
相关资源
最近更新 更多