我想从 Zend Framework 3 中的控制器中检索我的模块配置。我进行了搜索,似乎在 ZF2 中执行此操作的标准方法是使用
$this->getServiceLocator()
访问中的配置module.config.php
。但是,这在 ZF3 中不起作用,因为没有getServiceLocator()
方法。
实现这一目标的标准方法是什么?
我想从 Zend Framework 3 中的控制器中检索我的模块配置。我进行了搜索,似乎在 ZF2 中执行此操作的标准方法是使用
$this->getServiceLocator()
访问中的配置module.config.php
。但是,这在 ZF3 中不起作用,因为没有getServiceLocator()
方法。
实现这一目标的标准方法是什么?
不知道您是否找到了答案,因为 tasmaniski 写了不同的解决方案。以防万一,让我分享一个在我开始玩 ZF3 时会对我有很大帮助的东西:
MyControllerFactory.php
<?php
namespace My\Namespace;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use DependencyNamespace\...\ControllerDependencyClass; // this is not a real one of course!
class MyControllerFactory implements FactoryInterface
{
/**
* @param ContainerInterface $container
* @param string $requestedName
* @param null|array $options
* @return AuthAdapter
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
// Get config.
$config = $container->get('configuration');
// Get what I'm interested in config.
$myStuff = $config['the-array-i-am-interested-in']
// Do something with it.
$controllerDepency = dummyFunction($myStuff);
/*...the rest of your code here... */
// Inject dependency.
return $controllerDepency;
}
}
MyController.php
<?php
namespace My\Namespace;
use Zend\Mvc\Controller\AbstractActionController;
use DependencyNamespace\...\DependencyClass;
class MyController extends AbstractActionController
{
private $controllerDepency;
public function __construct(DependencyClass $controllerDepency)
{
$this->controllerDepency = $controllerDepency;
}
/*...the rest of your class here... */
}
您需要通过服务管理器注入您的依赖项。基本上,您需要创建 2 个类 Controller和ControllerFactory,它们将创建具有所有依赖项的 Controller。