我有一些基本的ZF2知识可用于创建普通项目。现在我想通过为其功能创建插件来创建一个可由用户社区扩展的模块。
我创建了像
这样的基本架构ModuleName
src
Service
MyService.php
Factory
Fun1Factory.php
Fun2Factory.php
Plugins
Fun1Plugins
PluginA.php
PluginB.php
Fun2Plugins
PluginC.php
PluginD.php
我创建了两个工厂类(不是来自zf2 factoryinterface)来处理各种类型的功能,如Fun1Factory.php& Fun2Factory.php。它们都通过invokables在module.config.php中注册。
'invokables' => array (
'Fun1Factory' => 'ModuleName\Factory\Fun1Factory',
'Fun2Factory' => 'ModuleName\Factory\Fun2Factory',
)
现在MyService实际上用特定插件的参数调用它们。如下所示。
$fun1Factory = $this->getServiceLocator()->get('Fun1Factory');
$fun1Factory->setSettings($settings['fun1']);
$this->fun1Plugin = $fun1Factory->getPlugin();
$this->fun1Plugin->init();
$fun2Factory = $this->getServiceLocator()->get('Fun2Factory');
$fun2Factory->setSettings($settings['fun2']);
$this->fun2Plugin = $fun2Factory->getPlugin();
$this->fun2Plugin->init();
因此可以像这样调用代码
$service = $this->getServiceLocator()->get('ModuleName\Service\MyService');
$service->init(array('fun1' => 'pluginA', 'fun2' => 'pluginD'));
我之前使用基本的MVC +工厂模式构建了类似的。但我不知道它应该如何构建到ZF2中。 ZF2提供工厂界面,但看起来非常类似于自动加载一些服务/控制器。如果他们有任何指导如何创建这样的模块?
更新:我也可以在MyService类中执行工厂代码。但我在想" ZF2 WAY"这样做。
更多细节:我有更多细节的更新问题。我在https://samsonasik.wordpress.com/2014/01/29/zend-framework-2-getting-closer-with-pluginmanager/找到的最接近的。但是我仍然需要动态地将插件注册到工厂而不是像下面那样静态注册。
protected $invokableClasses = array(
//represent invokables key
'xls' => 'Tutorial\Plugin\Xls',
'pdf' => 'Tutorial\Plugin\Pdf'
);
答案 0 :(得分:0)
如果您不希望插件创建者必须修改module.config.php中的service_manager,那么您有两个选择:
一个选项是创建一个Factory for MyService,它将在这些插件文件夹中查找它的依赖项。
其他选项是为MyService创建一个调用方法,将插件作为参数传递,然后创建插件实例。
但zf2的工作方式是使用module.config.php在service_manager中注册实例。因此,如果插件创建者可以使用service_manager会更好。
[UPDATE]
Zend FactoryInterface用于创建具有依赖关系的实例,因此这些依赖关系是从ServiceManager创建或提取的,然后通过构造函数注入到已为其创建工厂的实例中。
在您的情况下,您的插件开发人员必须为其插件创建工厂,并在service_manager中注册这些工厂。如果他们没有,那么你需要一种方法来了解插件是否具有依赖性。
希望这有帮助
Ismael Trascastro