我是ZendFramework3的新手,我只是想知道是否可以调用一个函数来使用更多的参数而不仅仅是工厂中的serviceManager(在我的Module类中):(是否可以通过$sm
参数旁边的参数?)
//class Module
//getConfig()
//getServiceConfig()
public function getControllerConfig()
{
return [
'factories' => [
Controller\ModuleController::class => function ($sm) {
return new ModuleController($sm);
}
]
];
}
答案 0 :(得分:1)
如果你想创造一个神奇的"工厂的所有依赖, 你应该看看SM AbstractFactory。
在那个工厂中,您可以从 $ requestedName 中查看依赖项。例如。你可以从类构造函数中读取依赖项,然后注入这些依赖项(或者从$ container中再次提取它)。您还可以在config中设置依赖项,这样就可以为所有类创建一个工厂。
答案 1 :(得分:0)
您可以(肯定地)将其他Arguments传递给Factory,只要要创建的Class可以优雅地处理Arguments。在下面的示例中,在Controller目录中创建了Factory类。现在是工厂 - 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
]
]
//...
];