尼古拉斯,我赞成你的回答。这是我到目前为止所做的。如果您认为我走在正确的道路上,请告诉我。
# URI's Explained for base "rest_api" (controller)
# collections resource
/collections/{id}
# contacts resource
/contacts/{id}
# collections contacts subresource
/collections/{collection_id}/contacts/{id}
Routed to
==> /contacts/id/{id}/collection_id/{collection_id}
在 Restful-terms 中,它有助于不考虑 SQL 和连接,而是更多地考虑集合、子集合和遍历。
一些例子:
# getting contact 3 who is in collection 1
# or simply checking whether contact 3 is in that collection (200 vs. 404)
GET /collections/1/contacts/3 ==> /contacts/id/3/collection_id/1
# getting contact 3 who is also in collection 3
GET /collections/3/contacts/3 ==> /contacts/id/3/collection_id/3
# adding contact 3 also to collection 2 (RELATIONSHIP)
PUT /collections/2/contacts/3 ==> /contacts/id/3/collection_id/2
# getting all collections of contact 3
GET /contacts/3/collections
# remove contact 3 from collection 1 (RELATIONSHIP)
DELETE /collections/1/contacts/3
# collection has a new contact, who is not yet added
POST /contacts
# from payload you get back the contacts insert id (44), now place contact in collection 1 (RELATIONSHIP)
PUT /collections/1/contacts/44
如您所见,我没有使用 POST 将联系人放置到集合中,而是使用 PUT 处理联系人与集合的 n:n 关系。
使用的 PHP CodeIgniter 路由如下。我真的不确定这是否需要,但允许上面提到漂亮的 URI。
// Collections
$route['rest_api/collections/(:num)'] = "rest_api/collections/id/$1";
// Collection Contacts Subresource
$route['rest_api/collections/(:num)/contacts'] = "rest_api/contacts/collection_id/$1";
$route['rest_api/collections/(:num)/contacts/(:num)'] = "rest_api/contacts/id/$2/collection_id/$1";
一些 rest_api 控制器方法有点长,但它似乎工作。如果使用,我必须获取 URI 请求参数和查询字符串参数。Phil 的 CodeIgniter REST API 必须稍微调整一下,以确保在执行 PUT 或 DELETE 请求时获取 URI 参数,因为这些值仅存在于 $this->get() 方法中;奇怪的。