Reputation: 2298
I'm trying to inject dependencies in a controller through controller factories. My module.config.php file contains
<?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
and controller file Controller\Api\SearchController contains
<?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 code
<?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);
}
}
While running above code it says
Too few arguments to function Commerce\Controller\Api\SearchController::__construct(), 0 passed in /var/www/html/zf3/vendor/zendframework/zend-servicemanager/src/Factory/InvokableFactory.php on line 30 and exactly 2 expected
What I'm missing here ? What is the best way to inject parameter/value dependencies in controllers?
Upvotes: 0
Views: 1073
Reputation: 2298
I got it working . In module.config.php file instead of using
'controllers' => [
'factories' => [
Controller\Api\SearchController::class => function ($container) {
return new Controller\Api\SearchController(
$container->get("first"),
$container->get("second")
);
},
]
]
I had to use
'controllers' => [
'factories' => [
Controller\Api\SearchController::class => function ($container) {
return new Controller\Api\SearchController(
"first",
"second"
);
},
]
]
Upvotes: 0