返回接口类型的抽象工厂类,找不到方法?

问题描述

我正在尝试使用抽象工厂模式。我创建了一个FactoryProducer,它根据传递给两个类方法之一的字符串创建一个特定于类的工厂。

我遇到的问题是我扩展了一个具体的工厂类,但 FactoryProducer 返回的接口类型不包含该方法。 VS Code 说该方法不存在。这是相关的代码

工厂生产者班

/**
 * Creates database or model factory.
 */
class FactoryProducer {
    /**
     * Creates a factory for the Model classes based on the given function argument.
     *
     * @param string $type The model class (e.g. 'asset','employee')
     * @return ModelFactoryInterface The given model's factory.
     */
    public static function getModelFactory(string $type) {
        switch($type) {
            case 'asset':
                return new \Inc\Models\AssetModelFactory;
                break;
            case 'application':
                //code here
                break;
        }
    }
}

混凝土工厂类AssetModelFactory

/**
 * The factory for the Asset class.
 */
class AssetModelFactory implements ModelFactoryInterface {

    /**
     * Create an empty Asset class object.
     *
     * @return Asset
     */
    function create(): Asset {
        return new Asset();
    }
    /**
     * Creates an Asset object instantiated with the given properties.
     *
     * @param array $props The properties for the class.
     * @return void
     */
    function createWithProps(array $props): Asset {
        $asset = new Asset();
        $keystocheck = ['name','companyName','type','label','location','employees','key'];
        if(\Inc\Base\Helpers::array_keys_exists($keystocheck,$props)) {
            $asset->setProperties($props['name'],$props['companyName'],$props['type'],$props['label'],$props['location'],$props['employees'],$props['key']);
            return $asset;
        }
        else {
            return new \WP_Error('incorrect_props','You did not include all of the necessary properties.');
        }
        
    }

}

我遇到的问题是第二种方法 createWithProps(array $props),因为接口不包含此方法

/**
 * The interface for model classes.
 */
interface ModelFactoryInterface {
    /**
     * Creates an object that extends AbstractModel
     *
     * @return AbstractModel
     */
    public function create(): AbstractModel;
}

如您所见,具体类对象扩展了抽象类。这是给出错误代码

$assetFactory = \Inc\Base\FactoryProducer::getModelFactory('asset');
$asset = $assetFactory->createWithProps($request); 

我想知道我是否错误地实现了抽象工厂类,或者这是否是 VS Code 的预期行为,因为 FactoryProducer 返回的具体类是基于参数的动态(例如,我已经将“资产”传递给 FactoryProducer::getModelFactory 方法,该方法最终将返回 AssetModelFactory 的实例,但官方返回类型为 ModelFactoryInterface)。

预先感谢您提供的任何建议。

解决方法

我能够弄清楚我做了什么。我习惯于像 C# 这样的编程语言,其中我可以在声明变量之前对其进行强类型化。我最终重构了代码,以便工厂拥有返回特定具体对象的方法,而不是使用 switch 语句:

class DBFactory implements DBFactoryInterface  {

    public static function createAsset(): AbstractDB { 
        return new \Inc\DB\AssetDB;
    }

    public static function createApplication(): AbstractDB { 
        return new \Inc\DB\ApplicationDB;
    }

    public static function createCompany(): AbstractDB { 
        return new \Inc\DB\CompanyDB;
    }
}