【发布时间】:2018-05-01 04:12:14
【问题描述】:
我正在尝试通过控制器工厂在控制器中注入依赖项。我的 module.config.php 文件包含
<?php
namespace Commerce;
use Commerce\Controller\Plugin\Website;
use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
return [
'router' => [
'routes' => [
'home' => [
'type' => Literal::class,
'options' => [
'route' => '/',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
'getFilters' => [
'type' => Segment::class,
'options' => [
'route' => '/api/getFilters',
'defaults' => [
'controller' => Controller\Api\SearchController::class,
'action' => 'getFilters'
]
]
],
'controllers' => [
'factories' => [
Controller\Api\SearchController::class => function ($container) {
return new Controller\Api\SearchController(
$container->get("first"),
$container->get("second")
);
},
Controller\IndexController::class => function ($container) {
return new Controller\IndexController();
},
Controller\Api\SearchController::class => InvokableFactory::class
]
]
// view_manager code
控制器文件 Controller\Api\SearchController 包含
<?php
namespace Commerce\Controller\Api;
class SearchController extends \Zend\Mvc\Controller\AbstractRestfulController
{
public function __construct($a, $b)
{
$this->a = $a;
$this->b = $b;
}
public function getFiltersAction()
{
// some code
}
}
Module.php 代码
<?php
namespace Commerce;
use Base\ModuleManager\Feature\ConfigProviderInterface;
use Zend\Mvc\MvcEvent; use Zend\Session\SessionManager;
class Module implements ConfigProviderInterface {
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
/**
* This method is called once the MVC bootstrapping is complete.
*/
public function onBootstrap(MvcEvent $event)
{
$application = $event->getApplication();
$serviceManager = $application->getServiceManager();
// The following line instantiates the SessionManager and automatically
// makes the SessionManager the 'default' one.
$sessionManager = $serviceManager->get(SessionManager::class);
}
}
运行上面的代码时会说
函数参数太少 Commerce\Controller\Api\SearchController::__construct(), 0 传入 /var/www/html/zf3/vendor/zendframework/zend-servicemanager/src/Factory/InvokableFactory.php 在第 30 行,预计正好 2 行
我在这里缺少什么?在控制器中注入参数/值依赖关系的最佳方法是什么?
【问题讨论】:
-
看起来你的控制器工厂设置被忽略了。你能发布整个module.config.php吗?还要添加 Module.php 代码,以防万一那里有问题。
-
@JannesBotis 我已经更新了代码。好心检查。一旦我删除了
Controller\Api\SearchController::class => InvokableFactory::class行,它就会说 无法“首先”将服务解析到工厂;你确定你是在配置时提供的吗?
标签: php dependency-injection zend-framework3