如何在Symfony2中使用多个存储库类?

时间:2013-05-15 09:11:45

标签: symfony

我正在Symfony 2.2中构建一个应用程序。

我为我的一个实体使用自定义存储库类。我把它包括在内:

@ORM\Entity(repositoryClass="MyApp\MainBundle\Entity\CategoryRepository")

我想在其他两个存储库类的类别中使用方法。

 @ORM\Entity(repositoryClass="Gedmo\Sortable\Entity\Repository\SortableRepository")
 @ORM\Entity(repositoryClass="Gedmo\Tree\Entity\Repository\NestedTreeRepository")

但是,实体只需要一个repositoryClass。如何将所有这三个存储库用于同一个实体?

2 个答案:

答案 0 :(得分:2)

我相信,每个实体只能有一个存储库。 所以你引用了 ORM\Entity(repositoryClass="MyApp\MainBundle\Entity\CategoryRepository")

如果您必须在存储库中使用其他存储库,

您可以获取这些存储库的EntityManager(如果不相同),例如:$em2 = whatEverIsTheEntity()

现在,您可以在CategoryRepository中将代理方法用于要使用的存储库中的方法。例如:$em2->getMethodFromEm2()

注意:但我 不会选择 以上解决方案,除非确实需要。我宁愿创建一个服务层,其中Doctrine Entity Manager为Dependency Injected。此服务层将连接到所有存储库并收集您想要实现的最终结果(在控制器中使用)。这样,代码也将更加清晰和可测试。

希望这会有所帮助。

答案 1 :(得分:1)

存储库是类(so entity)保留的。如果从超类继承(即使这些类不直接继承,但是repos可以),那么你可以使你的存储库(CategoryRepository)被其他两个扩展(一个扩展另一个,因为PHP没有允许多个类扩展名。)

非常类似

class NestedTreeRepository extends SortableRepository
{
}

class CategoryRepository extends NestedTreeRepository 
{
}

不知道这是否符合您的需求,但这是一种方式(我不会感到惊讶,如果是唯一的一种)来实现您在这里尝试做的事情