简体   繁体   中英

How to have a ZF2 web service run a function on route match

I've got a REST web service set up using ZF2, and what I want to do is have my web service call an intervening function before actually running the action associated to the route that was matched.

To be a bit more specific, but I want to do is, any time a route is matched for my module, to have a function run that inspects a value in the request header, and then either allows the action to be called or returns an error code.

For example, if I have the following route in my module.config.php :

'TestCall' => array(
    'type' => 'Segment',
    'options' => array(
        'route' => '/Rest/TestCall[/]',
        'defaults' => array(
            'controller' => 'Rest\Controller\Rest',
            'action' => 'TestCall',
        ),
    ),
),

And then, in RestController.php I have the following:

public function TestCallAction()
{
    return new JsonModel(array("I worked!"));
}

Whenever the route TestCall is matched, I would like to, before the action is fired , fire the following:

public function FireCheck()
{
    if ($this->getRequest()->getHeaders()->get('customheadervalue')->getFieldValue() == 'bananas')
    {
        //now fire the actual action
    }
    else
    {
        $this->getResponse()->setStatusCode(403);
        return new JsonModel(array("Nope, not allowed!"));
    }
}

Is this possible? Is there some way I can accomplish this? I'm pretty new to both Zend Framework and to PHP.

Thanks in advance for any help.

For the record, I managed to accomplish using information found here .

What I did was to add the following to my controller:

public function setEventManager(EventManagerInterface $events)
{
    parent::setEventManager($events);
    $controller = $this;
    $events->attach('dispatch', function ($e) use ($controller) {
        $request = $e->getRequest();
        $token = $request->getHeaders()->get('accesstoken')->getFieldValue();        

        if (!$token == "allowed")
        {
            return $controller->redirect()->toRoute('AccessDenied');
        }

        return;
    }, 100);
}

As well as adding this use statement to my controller:

use Zend\EventManager\EventManagerInterface;

This is binding a function to the dispatch event, which is fired, as far as I'm aware, after the request is received but before the route is actually processed. If the verification condition fails, the request is redirected to another route, otherwise the request is allowed to follow through to the expected route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM