您可以(当然)将其他参数传递给工厂,只要要创建的类可以优雅地处理参数。在下面的示例中,在控制器目录中创建了一个工厂类。这就是工厂——ModuleControllerFactory——实例化了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);
}
}
所以,现在我们可以创建 ModuleController 类的构造函数:
<?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
]);
}
}
现在,更新module.config.php
模块示例的配置文件夹内部: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
]
]
//...
];