在控制器的构造函数Zend Framework 2中获取请求参数

tas*_*ski 0 parameters constructor request zend-framework2

我在一个Controller中有10个动作.每个操作都需要ID来自请求.我想在构造函数中检查每个动作的ID,所以我想避免在每个动作中写入相同的代码10次.

显然,在构造函数中我不能使用如下函数:

$this->params()->fromQuery('paramname'); or 
$this->params()->fromRoute('paramname');
Run Code Online (Sandbox Code Playgroud)

那么,问题是如何在控制器的构造函数中获取请求参数?

Jur*_*man 8

简短的回答:你做不到.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');
    }
}
Run Code Online (Sandbox Code Playgroud)

或者如果你想直接给参数加水,这就是我经常这样做的方法:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用事件系统:挂钩到dispatch事件以获取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');
    }
}
Run Code Online (Sandbox Code Playgroud)

此功能在调度时起作用,执行loadId()方法,然后运行另一个(fooAction/barAction)方法.