如何为IDE记录magic(_call和_callStatic)方法

Rob*_*est 77 php documentation docblocks magic-methods phpstorm

在使用notepad ++和sublime编写许多快乐的岁月后,我被建议给PHP IDE一个机会.我正在尝试phpStorm,看起来不错.代码完成和文档是一个很好的功能,但是当使用魔术方法时,对我来说并不奏效.是否有工作让phpStorm了解魔术方法中发生了什么?

我们的情况是这样的:

abstract class a {
    public static function __callStatic($method,$args)
    {
        if(strpos($method,"get_by_") === 0)
        {
            //do stuff
        } elseif(strpos($method,"get_first_by_") === 0) {
            //do stuff
        } elseif($method == "get_all") {
            //do stuff
        }
    }
}

class b extends a {
    // some more stuff
}

b::get_by_user_id(27);
b::get_first_by_id(156);
b::get_all();
Run Code Online (Sandbox Code Playgroud)

神奇的callStatic方法允许我们通过构成函数调用的一个或多个参数来获取对象的集合.

我看到在这些情况下有一个@method语句可用,但phpStorm只是获取了这些语句中的第一个.此外,我只能将返回类型设置为混合,因为我更愿意将其设置为调用它的任何类(在我的示例中为b).

非常感谢任何想法或建议,谢谢.

Laz*_*One 134

使用类级别的PHPDoc注释 - 特别是@method标记 - 在PhpStorm中工作正常:

/**
 * @method static someClass get_by_user_id(int $id) Bla-bla
 * @method static someClass get_first_by_id(int $id) 
 */
abstract class a {
...
Run Code Online (Sandbox Code Playgroud)

在上面:

  • @method - PHPDoc标签
  • static - 告诉这是静态方法
  • someClass$this- 返回类型
  • get_by_user_id - 方法名称
  • (int $id) - 方法签名: ([[type] [parameter]<, ...>])
  • Bla-bla - 一些可选的描述

更多关于@method:

PS 虽然@method static在PhpStorm中工作正常(告诉IDE该方法是静态的)但实际的phpDocumentor工具可能不支持(但是?)(抱歉,暂时没有使用它).


或者 :(当然,在PhpStorm中)Settings | Inspections | PHP | Undefined | Undefined method --> Downgrade severity if __magic methods are present in class- 它无法以任何方式帮助完成此类方法的代码,但不会将这些魔术方法标记为"未定义方法"错误.


phpDocumentor关于为@property/ @methodtags 使用RegEx /部分名称的票证(它如何对文档有用,以及在处理代码完成时它对实际IDE的帮助有多少):

  • 谢谢,这看起来像是一个合理的建议,并且确实可以在phpStorm中使用,但是我有点讨厌在每个类的顶部写出@method的潜在几百行内容。您会看到get_by_ *方法可以由任何object参数添加,以通过指定参数获取该类型的对象。即使不包括get_by _ * _ and_ *的可能性,我最终也会在140个不同的类中得到大约1500个“ @methods”。有没有更通用的方式来提供文档? (2认同)
  • 仅供参考,phpDocumentor的票(所以其他用户知道你在说什么票;也把它添加到答案本身):https://github.com/phpDocumentor/phpDocumentor2/issues/689 (2认同)

Yau*_*hyk 6

与原始问题有些相关:

您还可以在 phpstorm 元文件中定义它。这是工厂方法(v2016.3)的示例:

// Define in .phpstorm.meta.php
namespace PHPSTORM_META {
    $STATIC_METHOD_TYPES = [
        \Factory::create('') => [],
    ];
}

// Then use in code
$factory = new \Factory();
$user = $factory->create(\User::class);
// Here you get autocomplete.
$user->subscribe();
Run Code Online (Sandbox Code Playgroud)

这样,当奇迹发生时,您就不必记录所有可能性。

有一些文档以了解详细信息。