Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
How to creating REST API subresources and without subresources?
  • Say I want to achieve something like this:

    /api/users/1/posts/1

    How would I do it?

    Far as I know, say if I only want the following:

    /api/users

    I will do:

    public function get_users()
    {

    }

    but if I want to let them specify a particular user 1 (or to accept a subresource parameter), say:
    /api/users/1
    its requires to be:

    public get_users($userid)
    {

    }

    But declaring same name is not allowed, so how can I achieve such behavior?

  • Never mind, I just notice I would write optional parameter and its all working fine.
    But its looks like as the sub-resources goes deeper, the logic within get_users will increasing as there is no way to separate the sub-resources into different function.

    i.e.
    /api/users/1/posts/1

    Will be
    public function get_users($userid = null, $subresource_dir = null, $subresource_id, $subresource_dir2, $subresource2_id ......)
    {
    if ($userid != null)
    {
    $subresources_result = $this->get_subresources($userid, subresource_dir , subresource_id);
    if ($subresources_result )
    {
    return $subresources_result ;
    }
    return $this->get_users_detail($userid)
    }
    return $this->get_users_detail();
    }
  • HarroHarro
    Accepted Answer
    You could use a route to rewrite /api/users/1/posts/1 to
    /api/userposts/1/1 and use a different controller for it?
  • I think you are right!

    So I guess if I want to do versioning the API, I can write route to rewrite

    /api/v1/users/1/posts/1 to /api/v1_userposts/1/1
    /api/v2/users/1/posts/1 to /api/v2_userposts/1/1

    etc...

    Thanks!

  • If you want to keep the code in a single controller, you can also give your controller a router() method. It gets both the method called and the arguments, so you can use that to dispatch the request to different methods.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion