我对创建普通项目有一些基本的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+Factory模式构建了类似的模式。但我不知道如何将它构建到ZF2中。ZF2提供了工厂接口,但看起来非常类似于自动加载一些服务/控制器。如果他们有指导如何创建这样的模块?
更新:我也可以在MyService类中执行工厂代码。但我正在考虑"ZF2方式"来做到这一点。
更多细节:我有更多细节的最新问题。我在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'
);
如果您不希望插件创建者必须在module.config.php中修改service_manager,那么您有两个选项:
一个选项是为MyService创建一个工厂,该工厂将在这些插件文件夹中查找其依赖项。
另一种选择是为MyService创建一个invoke方法,将插件作为参数传递,然后创建插件实例。
但是zf2的工作方式是使用module.config.php在service_manager中注册实例。因此,如果插件创建者能够使用service_manager会更好。
[更新]
Zend FactoryInterface用于创建具有依赖关系的实例,因此这些依赖关系是从ServiceManager中创建或提取的,然后通过构造函数将它们注入到为其创建工厂的实例中。
在您的情况下,插件开发人员必须为他们的插件创建工厂,并在service_manager中注册这些工厂。如果他们没有,那么你需要一种方法来知道插件是否有依赖关系。
希望这能帮助
Ismael Trascastro