I have PHP classes for each resource in a RESTful API. Depending on the request method it will be routed to call the right function. Here's an example for a GET call on the Users:
Class Users{
public function get($params){
// get information and return result
}
}
Requesting all users would be /api/users/
. Requesting a single user /api/users/:id
So far no problems.
Now my question: When requesting something like this /api/users/:id/posts
the API should return all posts made by the user with a specific id ( Posts
is another resource btw)
How would I implement this call in the PHP Class structure given above?
Handle it with the parameters in the get()
function in the resource Users
?
Add a new resource UsersPosts
?
Add a function in new method in the Users
class?
You should create a Router class that determines which controller class and method is called on a request (check out the some established frameworks like Symfony or Kohana to see how they handle routing for ideas, or even use them!). From there, whether you do Users::getPosts($userId)
or Posts:getByUserId($userId)
is up to you (to me, a UsersPosts
class indicates a cross-ref of some kind and may not be the best name for a controller or model).
It would be easier if you think of the 'user' as a filter to the posts resource than dealing with 2 different resources at the same time.
Something to look like this:
/api/posts/by_user/user_id
In this way you could keep only one resource per api page, and apply as many filters as you want.
/api/posts/by_user/USER_ID/category/videos/
Personally I go even further and have other criterias like order_by or order_dir in the url scheme, and they can all be appended to each other, and interchanged, like:
/api/posts/category/videos/by_user/USER_ID/order_by/title/order_dir/asc/limit/5
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.