我想使用一个具有扩展工厂常用功能的抽象基类,这有效,但我不知道如何准确指定返回类型并让它被PHPStorm检测到。
这是一个例子。有没有办法在PHPDoc中记录AppleFactory :: make()返回AppleInterface而OrangeFactory :: make()返回OrangeInterface?
<?php
namespace App\Factories;
abstract class AbstractFactory {
/** @var array $drivers */
protected $drivers;
/**
* instantiate the driver based on the given driver identifier
* @param string $driver Driver identifier.
* @return ???
* @throws UnknownDriverException If driver string is not in list of available drivers.
*/
public function make($driver) {
$class = $this->className($driver);
if (is_null($class))
throw new UnknownDriverException($driver);
return new $class;
}
/**
* get the full class name for the driver
* @param string $driver String mapping of class.
* @return string
*/
public function className($driver) {
return isset($this->drivers[$driver]) ? $this->drivers[$driver] : null;
}
}
class AppleFactory extends AbstractFactory {
protected $drivers = [
// both implement AppleInterface
'fuji' => \App\Apples\Fuji::class,
'gala' => \App\Apples\Gala::class
];
}
class OrangeFactory extends AbstractFactory {
protected $drivers = [
// both implement OrangeInterface
'navel' => \App\Oranges\Navel::class,
'blood' => \App\Oranges\Blood::class
];
}
答案 0 :(得分:2)
有没有办法在PHPDoc中记录
AppleFactory::make()
返回AppleInterface而OrangeFactory::make()
返回OrangeInterface?
根据您的上述要求 - 标准@method
应该完成工作 - 需要放在该类的PHPDoc评论中(相应地AppleFactory
和OrangeFactory
)。像这样:
@method AppleInterface make($driver)
同时,由于您将参数传递给工厂方法..并且返回的实例与此有很强的关系 - 请查看PhpStorm中的高级元数据支持(IDE特定功能)。这就是Laravel IDE帮助程序(例如)用来提供与此框架更好的IDE集成。
更多相关信息:https://confluence.jetbrains.com/display/PhpStorm/PhpStorm+Advanced+Metadata