donpvtzuux37724 2017-05-03 15:38
浏览 85
已采纳

PHPDoc具有扩展Factory模式的返回类型

I want to use an abstract base class with common functionality for factories to extend, which works, but I don't know how to accurately specify the return type and have it detected by PHPStorm.

Here's an example. Is there a way I can document in PHPDoc that AppleFactory::make() returns AppleInterface and OrangeFactory::make() returns 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
    ];

}
  • 写回答

1条回答 默认 最新

  • duanlongling5308 2017-05-03 17:10
    关注

    Is there a way I can document in PHPDoc that AppleFactory::make() returns AppleInterface and OrangeFactory::make() returns OrangeInterface?

    Based on your requirements above - a standard @method should do the job -- needs to be placed in PHPDoc comment for that class (AppleFactory and OrangeFactory accordingly). Something like this:

     @method AppleInterface make($driver)
    

    At the same time, since you do pass parameter to a factory method .. and returned instance has strong relation to that -- have a look at Advanced Metadata support in PhpStorm (IDE specific functionality). This is what Laravel IDE helper (for example) uses to provide better IDE integration with this framework.

    More on this: https://confluence.jetbrains.com/display/PhpStorm/PhpStorm+Advanced+Metadata

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊