【问题标题】:PHP/Doctrine2 - Implement an interface twicePHP/Doctrine2 - 两次实现一个接口
【发布时间】:2013-11-23 19:51:44
【问题描述】:

这可能是一个愚蠢的问题。我正在尝试为 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,它也扩展了ObjectRepositorySelectable。所以TestImplementation 本质上是两次实现ObjectRepositorySelectable(或者是吗?)。它编译得很好,但这是一种有效的方法吗?

【问题讨论】:

    标签: php oop unit-testing doctrine-orm


    【解决方案1】:

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

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

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

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

    在混合接口方面,寻找兼容性问题而不是继承问题。

    【讨论】:

      猜你喜欢
      • 2017-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 2019-08-04
      • 2023-03-06
      相关资源
      最近更新 更多