0

这可能是一个愚蠢的问题。我正在尝试为 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){
        //...
    }
}

为了将所有内容联系在一起,我TestRepositoryInterfaceRepositoryInterfaceObjectRepositorySelectable.

interface TestRepositoryInterface extends RepositoryInterface, ObjectRepository, Selectable{

}

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

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

或者,如果我进行单元测试,创建模拟对象或测试存根会很容易。

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

4

1 回答 1

0

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

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

假设您有一个接口,其实现需要迭代。你可能会让它实现\IteratorAggregate

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

当涉及到混合接口时,寻找兼容性问题而不是继承问题。

于 2013-11-12T20:49:21.430 回答