使用Zend插件管理器实现工厂模式

时间:2019-04-29 16:58:39

标签: php zend-framework3

函数createInstance(String $instance) : InstanceInterface{}应该返回IntanceInterface的实例。我不想使用switch语句,因为实例太多(不同的类)。尽管有朋友告诉我有关Zend-Framework 3中的插件管理器的信息。 我阅读了有关Service Manager的信息,因为它们似乎相关。

https://olegkrivtsov.github.io/using-zend-framework-3-book/html/en/Website_Operation/Plugin_Managers.html

关于Service Manager的文档和描述都很好,而不是Plugin Manager。

我认为我以错误的方式实现了它,因为遇到了php错误:

Deprecated: Zend\ServiceManager\AbstractPluginManager::__construct now expects a Interop\Container\ContainerInterface instance representing the parent container; please update your code in /website/admin/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php on line 85

Warning: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time in /website/admin/vendor/zendframework/zend-session/src/Config/SessionConfig.php on line 148

InstanceFactory

protected $instancePluginManager;

public function __construct(InstancePluginManager $instacePluginManager)
    {
        $this->instancePluginManager = $instancePluginManager;
    }


public function createInstance(string $instance) :InstanceInterface
    {

       $this->instacePluginManager->get($instance);
}

InstancePluginManager

class InstancePluginManager extends AbstractPluginManager
{


    protected $instanceOf = InstanceInterface::class;

    /**
     * @var string[]|callable[] Default factories
     */
    protected $factories = [

        A::class => InvokableFactory::class,
        B::class => InvokableFactory::class,
        C::class => InvokableFactory::class,
        D::class => InvokableFactory::class,
        E::class => InvokableFactory::class,
        F::class => InvokableFactory::class,
        G::class => InvokableFactory::class,
        H::class => InvokableFactory::class,
        I::class => InvokableFactory::class,
        J::class => InvokableFactory::class,
    ];

    public function validate($instance)
    {
        if (! $instance instanceof $this->instanceOf) {
            throw new InvalidServiceException(sprintf(
                'Chart of type "%s" is invalid; must implement %s',
                (is_object($instance) ? get_class($instance) : gettype($instance)),
                $this->instanceOf
            ));
        }
    }
}

InstanceFactoryFactory(Zend Factory)

class InstanceFactoryFactory implements FactoryInterface
{

    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $instancePluginManager = $container->get(InstancePluginManager::class);

        return new InstanceFactory($instancePluginManager);
    }
}

module.config.php

return [
'service_manager' => [
        'factories' => [
InstanceFactory::class => InstanceFactoryFactory::class,
InstancePluginManager::class => InvokableFactory::class,

],
],
];

1 个答案:

答案 0 :(得分:1)

更改

sed

$PATH

InvokableFactory试图创建不带参数的InstancePluginManager。