質問

I'm using Apigility to build my Rest APIs.

I want to build have the ability to take in multiple parameters. Such as

http://mydomain.com/users/1/activities/4

I now this is possible from this page: https://github.com/zfcampus/zf-apigility/issues/10

I have edit my module route to:

'route' => '/users/:users_id/activities[/:activities_id]',

But, I don't know how to retrieve users_id from the url.

I tried grabbing the params in my Resource php

    $evt = $this->getEvent();
    $params = $evt->getParams();
    die(var_dump($params));

But, that only returns

object(ArrayObject)#748 (1) {
  ["storage":"ArrayObject":private]=>
  array(1) {
    ["id"]=>
    string(1) "4"
  }
}

I'm a little baffled. Please advice.

Thanks!

役に立ちましたか?

解決

In Zend Framework 2, you can use the RouteMatch to get the parameters of a route. For your case, you could try this :

    $e = $this->getEvent();
    $route = $e->getRouteMatch();
    $usr_id = $match->getParam('users_id');

The user_id is now in the $usr_id variable.

他のヒント

Inside my controller i get them params like this.

$this->Params('users_id');

Same way you can get it for activities. Or

$this->getEvent()->getRouteMatch()->getParam('users_id');

if your url was example.com/users?users_id=123&activites_id=123 then you could get both by calling

$this->params()->fromQuery()

and the result would be

Array (
    [users_id] => 123
    [activities_id] => 123
)

The best method is like this, you do a number of things in a single line of code and as far as I am concerned this is best practice:

    $user_id    = (int) $this->params()->fromRoute('users_id', 0);
    $activities_id    = (int) $this->params()->fromRoute('activities_id', 0);
  1. You know the ID should be an integer so you cast this.
  2. If the users_id is not mandatory, it will be set to 0 which you can then run a check against...

    if (0 === $user_id) {
        //Do some stuff
    }
    

This is how I do pretty much all my routes.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top