如何为 IDE 编写魔法(_ call 和_callStatic)方法的文档

在使用记事本 + + 和卓越编码了许多年之后,有人建议我尝试使用 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();

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

我看到在这些情况下有一个@method 语句,但是 phpStorm 只选择了其中的第一个语句。此外,我只能将返回类型设置为混合类型,因为我希望能够将其设置为调用该类的任何类(在我的示例中为 b)。

如有任何意见或建议,我们将不胜感激,谢谢。

38181 次浏览

Use class-level PHPDoc comment -- specifically @method tag -- works fine in PhpStorm:

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

In the above:

  • @method -- PHPDoc tag
  • static -- tells that this is static method
  • someClass or $this -- return type
  • get_by_user_id -- method name
  • (int $id) -- method signature: ([[type] [parameter]<, ...>])
  • Bla-bla -- some optional description

More about @method:

P.S. While @method static works fine in PhpStorm (tells IDE that method is static) it may not be (yet?) supported by actual phpDocumentor tool (sorry, have not used it for a while).


Alternatively: (in PhpStorm, of course) Settings | Inspections | PHP | Undefined | Undefined method --> Downgrade severity if __magic methods are present in class -- it will not help with code completion for such methods in any way, but will not mark those magic methods as "undefined method" errors.


phpDocumentor's ticket regarding using RegEx/partial names for @property/@method tags (how it can be useful for documentation and how little help it may bring to the actual IDE when dealing with code completion):

Somewhat related to original question:

You can also define this in phpstorm meta file. Here's an example for factory method (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();

This way you don't have to docblock every possibility when magic happens.

Have some docs for details.