3 php zend-framework zend-framework3 zend-servicemanager
我正在尝试在控制器中获取 ServiceManager 实例以使用 Db\Adapter 工厂。
我添加到 module/Application/config/module.config.php:
'service_manager' => [
'factories' => [
Adapter::class => AdapterServiceFactory::class,
],
],
Run Code Online (Sandbox Code Playgroud)
在 config/autoload/local.php 中,我添加了以下几行:
'db' => [
'driver' => 'Mysqli',
'database' => 'mydb',
'username' => 'myuser',
'password' => 'mypassword',
]
Run Code Online (Sandbox Code Playgroud)
现在我想访问我的 module/Application/src/Controller/IndexController.php 中的 ServiceManager。我怎么做?
我尝试过$sm = $this->getPluginManager();但没有成功。如果我$serviceManager->get(Adapter::class)使用 PluginManager 运行它会给我一个错误:
Too few arguments to function Zend\Db\Adapter\Adapter::__construct(), 0 passed in (...)\vendor\zendframework\zend-servicemanager\src\Factory\InvokableFactory.php on line 30 and at least 1 expected
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能获得一个 ServiceManager 来获取我的适配器对象?
我改变了控制器工厂
'controllers' => [
'factories' => [
Controller\IndexController::class => InvokableFactory::class,
],
],
Run Code Online (Sandbox Code Playgroud)
到
'controllers' => [
'factories' => [
Controller\IndexController::class => function(ContainerInterface $serviceManager) {
return new Controller\IndexController($serviceManager);
},
],
],
Run Code Online (Sandbox Code Playgroud)
我还在 module.config.php 中添加了一个 getServiceConfig() 方法,并向接收 ServiceManager 的 IndexController 添加了一个构造函数。现在我可以访问控制器内部了。
但我现在的问题是:是否有更好、更“类似 zend”的方式来实现这一目标?
小智 5
感谢 SO 的相关主题,我终于找到了答案。ZF3 中的服务管理器
这似乎是通过使用控制器工厂来完成的,几乎就像我一样。