如何处理php REST url资源 [英] how to process php REST url resources
问题描述
我在 php 文章中阅读了很多关于 REST api 的内容.但我还是很困惑.
I have read many about REST api in php articles. but I still get quite confusing.
他们基本上是将url重写为index.php,由index.php处理url并依赖于方法,然后发送响应
they basically rewrite the url to a index.php, which process the url and depends on the method, then send response
但是哪个是处理 url 的正确方法?这看起来不正确...
but which is the properly way to process the url? this looks doen't look correct...
- 获取uri并拆分它
- 我应该知道如何处理每个部分,例如.对于 GET/usr/1 我应该做类似的事情:
if($myUri[0]=="usr")
getUser($myUri[1]);
如果请求 url 类似于 GET www.domain.com/user/1
它会调用 getUser($id);
但是如果您还可以通过姓名或电子邮件检索用户,会发生什么?所以网址也可以是 www.domain.com/user/john
或 www.domain.com/user/john@gmail.com
每个 url 应该调用不同的方法,如 getUsrByName($name)
或 getUsrByEmail($mail)
if the request url is like GET www.domain.com/user/1
it would call getUser($id);
but what happen if you can also retrieve the user by name, or maybe e-mail? so the url can also be www.domain.com/user/john
or www.domain.com/user/john@gmail.com
and each url should call different methods like getUsrByName($name)
or getUsrByEmail($mail)
推荐答案
处理这个问题的正确方法是使用这样的 URL:
The proper way of handling this would be to have URLs like this:
domain.com/user/id/1 -> user::getById
domain.com/user/email/foo@bar.com -> user::getByEmail
domain.com/user/username/foo -> user::getByUsername
但是,指定多个参数"更像是搜索,我反对为此使用资源,因为路径应该是绝对的.这意味着:
However, specifying multiple "parameters" is more like a search, I'd go against using resources for that, because a path should be absolute. Which means:
domain.com/user/name/Kossel/likes/StackOverflow
还有:
domain.com/user/likes/StackOverflow/name/Kossel
不是同一个资源.相反,我会这样做:
Are not the same resource. Instead I'd do:
domain.com/user/?name=Kossel&likes=StackOverflow
这是 Stack Overflow 使用的:
This is what Stack Overflow uses:
stackoverflow.com/questions/tagged/php
stackoverflow.com/tags/php/new
stackoverflow.com/questions/tagged/mysql?sort=featured
这篇关于如何处理php REST url资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!