简短的回答:你不能。不幸的是,插件(您在这里使用params)在构建后可用。
有两种方法可以使您的代码 DRY:提取方法和使用事件系统执行提取。
提取方法:最简单的一种:
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');
}
}
或者如果你想直接水合参数,我经常这样做:
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;
}
}
使用事件系统:您挂钩到调度事件以获取 id 并在执行操作之前设置它:
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');
}
}
此功能在调度时起作用,执行 loadId() 方法,然后运行另一个 (fooAction/barAction) 方法。