You may (for sure) pass other Arguments to Factory, so long as the Class to be created can handle the Arguments gracefully. In the example below, a Factory Class was created inside the Controller Directory. This is now the factory- ModuleControllerFactory - that instantiates the ModuleController.
<?php
namespace Application\Controller;
use Application\Controller\ModuleController,
Zend\ServiceManager\Factory\FactoryInterface,
Zend\ServiceManager\Factory,
Interop\Container\ContainerInterface;
class ModuleControllerFactory implements FactoryInterface {
public function __invoke(ContainerInterface $container, $requestedName, array $options=null){
// WE WANT TO PASS $variable1 to $variable12 TO THE ModuleController
$variable1 = "Variable Value 1";
$variable2 = "Variable Value 2";
$variable3 = "Variable Value 3";
return new ModuleController($container, $variable1, $variable2, $variable3);
}
}
So, now we can create the Constructor of the ModuleController Class:
<?php
// FILE-NAME: ModuleController.php;
namespace Application\Controller;
use Interop\Container\ContainerInterface;
class ModuleController extends AbstractActionController {
/**
* ContainerInterface.
* @var ContainerInterface
*/
public $container;
/**
* @var string
*/
public $var1;
/**
* @var string
*/
public $var2;
/**
* @var string
*/
public $var3;
// CONTAINER & VARIALBLES INJECTED IN CONSTRUCTOR
public function __construct(ContainerInterface $container, $variable1=null, $variable2=null, $variable3=null) {
$this->container = $container;
$this->var1 = $variable1;
$this->var2 = $variable2;
$this->var3 = $variable3;
}
// JUST PLAY WITH THE INJECTED VALUES IN THE INDEX ACTION
public function indexAction() {
return new ViewModel([
'container' => $this->container,
'var1' => $this->var1,
'var2' => $this->var2,
'var3' => $this->var3
]);
}
}
And now, update the module.config.php
inside the config Folder of your module Example: module/Application/config/module.config.php
.
<?php
namespace Application;
use Zend\Router\Http\Literal;
use Zend\Router\Http\Regex;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
return [
//...
'router' => [
//...
],
'controllers' => [
'factories' => [
Controller\ModuleController::class => Controller\ModuleControllerFactory::class
]
]
//...
];