PHP Doc - 如何指定确切的抽象类型?

标签 php interface phpstorm abstract phpdoc

想象一下以下抽象接口(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/

相关文章:

javascript - 哪个是适合开发以 php 作为后端的单页应用程序的 javascript 框架?

java - 接口(interface)是否提供完整的抽象?如何?

在 TCL 代码中从 C (example.i) 调用函数

laravel - 无法在 PhpStorm 10.0.3 上添加 Artisan 命令行工具

Windows 本地主机上的 PhpStorm 和 xdebug 探查器设置

javascript - 如何使用JS获取href值?

php - $this->something() || 是做什么的PHP 速记/快捷方式中的 somefunction($somevar) 是什么意思?

go - 如何在不更改golang中原始值的情况下修改对象的值副本?

html - 属性的 PhpStorm HTML 缩进

php - 查询时的 CodeIgniter 索引数组