这可能是一个愚蠢的问题。我正在尝试为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
RepositoryInterface
,ObjectRepository
和Selectable
进行了延伸。
interface TestRepositoryInterface extends RepositoryInterface, ObjectRepository, Selectable{
}
然后我可以通过直接注入传递TestRepositoryInterface
的实现:
class TestImplementation extends AbstractRepository implements TestRepositoryInterface{
//...
}
或者如果我是单元测试,那么创建模拟对象或测试存根很容易。
我唯一担心的是TestImplementation
课程。它扩展了AbstractRepository
,它已经实现了ObjectRepository
和Selectable
(通过EntityRepository
),同时TestImplementation
也实现了TestRepositoryInterface
,它也扩展了ObjectRepository
Selectable
和TestImplementation
。所以ObjectRepository
基本上实施了Selectable
和{{1}}两次(或者是它?)。它编译得很好,但这是一种有效的方法吗?
答案 0 :(得分:0)
一个类完全可以实现多个接口,这些接口又可以扩展通用接口。方法是相同的,所以没有冲突。
您唯一需要担心的是使用相同的命名方法实现接口,但使用替代参数。
假设您有一个需要迭代实现的接口。您可能会实现\IteratorAggregate
。
现在假设您的实现类扩展ArrayCollection
(来自普通学说)。因为ArrayCollection
也实现了IteratorAggregate
,所以它会为您处理一些自己的接口定义。
在混合接口时,请查找兼容性问题而不是继承问题。