想象一下以下抽象接口(interface)
interface IDomainRepository {
/**
* Finds a Domain Object by the Id
*
* @param int $id the id of the object
*
* @return IDomainObject the domain object
*/
public function findById($id);
//More than that method...
}
现在是一个从 IDomainRepository 扩展的特定接口(interface)
interface IUserRepository extends IDomainRepository {
//More than only extending...
}
如果我调用这样的东西,我想在此处键入提示而无需额外注释(因为我经常使用它)。
function foo(IUserRepository $repo) {
$user = $repo->findById(42)
//Typehint User without @var User $user
}
目前我这样做:
/**
* Interface IUserRepository
* @method User findById($id)
*/
interface IUserRepository extends {
}
但是“@method”参数用于隐藏的魔法方法。所以这感觉是不对的。有更好的解决方案吗?
我应该没有基本接口(interface),只有特定的接口(interface)(这意味着复制和粘贴大约 20 个方法签名吗?
最佳答案
由于 PHP 中没有返回类型提示,但大多数时候都是关于首选项,根据所使用的 IDE,使用 @method
标记或 docblock 作为附加方法可能没有区别声明,所以....
请注意,您不一定要移动这些方法(并且您很可能无论如何都不想这样做,因为这会使 IDomainRepository
的实现不需要findById()
方法),但您可以在必要时在扩展接口(interface)中简单地重新声明/覆盖它们,并提供正确的文档 block ,如 @Deele 所示:
interface IUserRepository extends IDomainRepository {
/**
* Finds a User by Id
*
* @param int $id the id of the object
*
* @return IUserRepository the User object
*/
public function findById($id);
}
我个人认为使用 @method 更干净,因为它更清楚 findById()
的具体实现应该如何表现(只需查看在方法声明的代码中),并且它预计与基本接口(interface)不同。
顺便说一句,有一天这也可能与 PHP RFC: Return Type Declarations 中提出的协变返回类型提示“兼容”。 :
// Covariant return-type:
interface Collection {
function map(callable $fn): Collection;
}
interface Set extends Collection {
function map(callable $fn): Set;
}
关于PHP Doc - 如何指定确切的抽象类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24482313/