【问题标题】:PHPDoc @return type equals class field type (in PhpStorm 10.0.4)PHPDoc @return 类型等于类字段类型(在 PhpStorm 10.0.4 中)
【发布时间】:2017-02-06 23:52:18
【问题描述】:

所以我有一个 trait,如下所示:

trait RepositoryTrait
{
    /**
     * Find a model by its primary key.
     *
     * @param int $id
     * @param array $columns
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function find($id, array $columns = ['*'])
    {
        return $this->query()->find($id, $columns);
    }
}

和界面:

interface Repository
{
    /**
     * Find a model by its primary key.
     *
     * @param int $id
     * @param array $columns
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function find($id, array $columns = ['*']);
}

我有类似的存储库类:

class FixedAssetRepository implements Repository
{
    use RepositoryTrait;

    /**
     * FixedAsset model.
     *
     * @var FixedAsset
     */
    protected $model;

    /**
     * Repository constructor.
     *
     * @param FixedAsset $fixedAsset
     */
    public function __construct(FixedAsset $fixedAsset)
    {
        $this->model = $fixedAsset;
    }
}

而我正在寻找的是以某种方式定义方法 find(在 trait 或接口中)是 FixedAsset 的类型 - 但这应该始终适用于我将创建的每个新 Repository 类(实现了 Repository 接口)。

我需要它在 PhpStorm 10.0.4

中进行类型提示

有可能吗?

所以结果应该是当我在某处打电话时,即:

$fixedAsset = $this->fixedAssetRepositry->find($id);

PhpStorm 会知道 $fixedAsset 是类 FixedAsset 的对象,而不仅仅是 \Illuminate\Database\Eloquent\Model(现在就是这样工作的)。

所以我需要类似界面(或特征?)的东西:

   /**
     * Find a model by its primary key.
     *
     * @param int $id
     * @param array $columns
     * @return $this->model
     */
    public function find($id, array $columns = ['*']);

当然@return $this->model 不起作用。

如有任何建议,我们将不胜感激。

【问题讨论】:

  • 现在能想到的最好的方法是使用@method 并以正确的返回类型“重新声明”它——看看这是否可行。
  • 太棒了!多么简单……这就是我需要的。非常感谢。您可以发布此答案,我可以将其标记为解决方案。

标签: laravel phpstorm phpdoc


【解决方案1】:

我现在能想到的唯一解决方案是在 PHPDoc 注释中对 FixedAssetRepository 类使用 @method 并“重新声明”具有正确签名(返回类型)的 find() 方法。由于它是一个 PHPDoc 解决方案,因此在运行时不会对 PHP 代码产生任何影响。

示例代码:

/**
 * @method FixedAsset find(int $id, array $columns) Find a model by its primary key
 */
class FixedAssetRepository implements Repository
{
...

更多关于 @method 标签 -- https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md#711-method

【讨论】:

    猜你喜欢
    • 2015-07-22
    • 2018-08-16
    • 2016-09-27
    • 2016-08-30
    • 1970-01-01
    • 2021-06-03
    • 2020-05-11
    • 2021-09-21
    • 2016-05-01
    相关资源
    最近更新 更多