我正在尝试在我的 Controller 中获取一个 ServiceManager 实例以使用 Db\Adapter 的工厂。
我添加到 module/Application/config/module.config.php:
'service_manager' => [
'factories' => [
Adapter::class => AdapterServiceFactory::class,
],
],
我在 config/autoload/local.php 添加了以下几行:
'db' => [
'driver' => 'Mysqli',
'database' => 'mydb',
'username' => 'myuser',
'password' => 'mypassword',
]
现在我想访问我的模块/Application/src/Controller/IndexController.php 中的ServiceManager。我该怎么做?
我尝试了 $sm = $this->getPluginManager();
但没有成功。如果我使用 PluginManager 运行 $serviceManager->get(Adapter::class)
它会给我一个错误:
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
我该怎么做才能获得一个 ServiceManager 来获取我的 Adapter 对象?
我改变了 Controller 工厂
'controllers' => [
'factories' => [
Controller\IndexController::class => InvokableFactory::class,
],
],
到
'controllers' => [
'factories' => [
Controller\IndexController::class => function(ContainerInterface $serviceManager) {
return new Controller\IndexController($serviceManager);
},
],
],
我还向 module.config.php 添加了一个 getServiceConfig() 方法,并向接收 ServiceManager 的 IndexController 添加了一个构造函数。现在我可以访问 Controller 内部了。
但我现在的问题是:是否有更好、更“类似 zend”的方法来实现这一目标?
最佳答案
感谢 SO 的相关主题,我终于找到了答案。 ServiceManager in ZF3
这似乎是通过使用 Controller Factories 完成的,几乎就像我所做的那样。
关于php - 如何在 zend framework 3 的 Controller 中获取服务管理器实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42594473/