从非zend应用程序访问ZF2模块服务


Access ZF2 module service from non-Zend application

我正在构建一个带有多个模块的Zend应用程序。我想在其他不使用Zend框架的项目中重用这些模块中的一些。

我已经在非Zend测试脚本中使用了包含init_autolloader .php,并且可以像预期的那样访问Zend框架类。

我还可以设置我的自动加载器来直接从我的模块加载类。

我要做的是加载模块,并从getServiceConfig()函数的module类访问它的服务。

使用ModuleManager,我已经设置了DefaultListeners并可以加载模块。

use Zend'ModuleManager'Listener;
use Zend'ModuleManager'ModuleManager;
chdir(dirname(__DIR__));
// Instantiate and configure the default listener aggregate
$listenerOptions = new Listener'ListenerOptions(array(
    'module_paths' => array(
        './module',
        './vendor'
    )
));
$defaultListeners = new Listener'DefaultListenerAggregate($listenerOptions);
// Instantiate the module manager
$moduleManager = new ModuleManager(array(
    'Group',
));
// Attach the default listener aggregate and load the modules
$moduleManager->getEventManager()->attachAggregate($defaultListeners);
$moduleManager->loadModules();

我想做的是实例化ServiceManager的实例,并能够从模块中获取服务,因为我可以在应用程序中。

任何帮助都将非常感激。

谢谢。

您可以像这样创建服务管理器:

use Zend'Mvc'Service'ServiceManagerConfig;
use Zend'ServiceManager'ServiceManager;
/* Insert your code to setup whatever autoloader you want */
$configuration = include 'config/application.config.php';
$serviceManager = new ServiceManager(new ServiceManagerConfig());
$serviceManager->setService('ApplicationConfig', $configuration);
$serviceManager->get('ModuleManager')->loadModules();

如果您只想使用一个特定的模块,那么创建一个只包含您想要的模块的config/application.config.php副本。注意,如果您愿意,可以将配置数组直接放在上面代码中的$configuration中,而不是包含一个文件。