我试图在我的控制器中获取一个 ServiceManager 实例,以便为 Db\Adapter 使用工厂。
我添加到模块/应用程序/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();
没有成功。如果我$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
我该怎么做才能获得一个 ServiceManager 来获取我的那个 Adapter 对象?
我将控制器工厂从
'controllers' => [
'factories' => [
Controller\IndexController::class => InvokableFactory::class,
],
],
至
'controllers' => [
'factories' => [
Controller\IndexController::class => function(ContainerInterface $serviceManager) {
return new Controller\IndexController($serviceManager);
},
],
],
我还在 module.config.php 中添加了一个 getServiceConfig() 方法,并向 IndexController 添加了一个构造函数,它接收 ServiceManager。现在我可以访问控制器内部了。
但我现在的问题是:是否有更好、更“类似 zend”的方式来实现这一目标?