PHP / Doctrine2 - 实现两次接口

时间:2013-11-11 21:13:09

标签: php oop unit-testing doctrine-orm

这可能是一个愚蠢的问题。我正在尝试为Doctrine 2创建一个通用的存储库接口,所以我可以通过直接注入将它传递给我的控制器:

//TestController.php

public function __construct(TestRepositoryInterface $p_repository){
    //...
}

Doctrine2中EntityRepository的方法签名如下:

class EntityRepository implements ObjectRepository, Selectable{
    //...
}

EntityRepository缺少一些我希望在存储库中添加的功能(添加,删除,更新)。所以我创建了一个基本存储库接口和一个抽象存储库类来封装这些函数:

interface RepositoryInterface {
    public function add($entity);
    public function delete($entity);
    public function update($entity);
}

抽象存储库类从EntityRepository扩展,因此我仍然可以获得EntityRepository的功能。

abstract class AbstractRepository extends EntityRepository{
    public function add($entity){
        //...
    }

    public function add($entity){
        //...
    }

    public function add($entity){
        //...
    }
}

为了将所有内容联系在一起,我TestRepositoryInterface RepositoryInterfaceObjectRepositorySelectable进行了延伸。

interface TestRepositoryInterface extends RepositoryInterface, ObjectRepository, Selectable{

}

然后我可以通过直接注入传递TestRepositoryInterface的实现:

class TestImplementation extends AbstractRepository implements TestRepositoryInterface{
    //...
}

或者如果我是单元测试,那么创建模拟对象或测试存根很容易。

我唯一担心的是TestImplementation课程。它扩展了AbstractRepository,它已经实现了ObjectRepositorySelectable(通过EntityRepository),同时TestImplementation也实现了TestRepositoryInterface,它也扩展了ObjectRepository SelectableTestImplementation。所以ObjectRepository基本上实施了Selectable和{{1}}两次(或者是它?)。它编译得很好,但这是一种有效的方法吗?

1 个答案:

答案 0 :(得分:0)

一个类完全可以实现多个接口,这些接口又可以扩展通用接口。方法是相同的,所以没有冲突。

您唯一需要担心的是使用相同的命名方法实现接口,但使用替代参数。

假设您有一个需要迭代实现的接口。您可能会实现\IteratorAggregate

现在假设您的实现类扩展ArrayCollection(来自普通学说)。因为ArrayCollection也实现了IteratorAggregate,所以它会为您处理一些自己的接口定义。

在混合接口时,请查找兼容性问题而不是继承问题。