在控制器的构造函数Zend Framework 2中获取请求参数 [英] Get request parameters in controller's constructor Zend Framework 2
问题描述
我在一个控制器有10个动作。每个操作都需要来自请求的ID。
我想在每个动作的构造函数中检查ID,所以我想避免在每个动作中写相同的代码10次。
I have 10 actions in one Controller. Every action required ID from request. I want to check ID in constructor for every action, so I want avoid to write the same code 10 times in every action.
显然,在构造函数中无法使用以下函数:
obviously, In constructor I can not use functions like:
$this->params()->fromQuery('paramname'); or
$this->params()->fromRoute('paramname');
所以,问题是如何在控制器的构造函数中获取请求参数?
So, the question is how to get request params in controller's constructor?
推荐答案
简短的答案:你不能。
Short answer: you cannot. The plugins (you are using params
here) are available after construct, unfortunately.
有两种方法可以在构建后使用 params
您的代码DRY:提取方法并使用事件系统执行提取。
There are two ways to make your code DRY: extract a method and perform extraction with the event system.
提取方法:最简单的方法:
class MyController
{
public function fooAction()
{
$id = $this->getId();
// Do something with $id
}
public function barAction()
{
$id = $this->getId();
// Do something with $id
}
protected function getId()
{
return $this->params('id');
}
}
或者如果要直接是我经常这样做:
Or if you want to hydrate the parameter directly, this is how I do this quite often:
class MyController
{
protected $repository;
public function __construct(Repository $repository)
{
$this->repository = repository;
}
public function barAction()
{
$foo = $this->getFoo();
// Do something with $foo
}
public function bazAction()
{
$foo = $this->getFoo();
// Do something with $foo
}
protected function getFoo()
{
$id = $this->params('id');
$foo = $this->repository->find($id);
if (null === $foo) {
throw new FooNotFoundException(sprintf(
'Cannot find a Foo with id %s', $id
));
}
return $foo;
}
}
使用事件系统 :你钩入dispatch事件来抓取id并在执行动作之前设置它:
With the event sytem: you hook into the dispatch event to grab the id and set it prior to execution of the action:
class MyController
{
protected $id;
public function fooAction()
{
// Use $this->id
}
public function barAction()
{
// Use $this->id
}
protected function attachDefaultListeners()
{
parent::attachDefaultListeners();
$events = $this->getEventManager();
$events->attach(MvcEvent::EVENT_DISPATCH, array($this, 'loadId'), 100);
}
public function loadId()
{
$this->id = $this->params('id');
}
}
此功能与dispatch方法被执行,然后另一个(fooAction / barAction)方法被运行。
This feature works as upon dispatch, the loadId() method is executed and then the other (fooAction/barAction) method is ran.
这篇关于在控制器的构造函数Zend Framework 2中获取请求参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!