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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀