开发者

how to process php REST url resources

I have read many about REST api in php articles. but I still get quite confusing.

they basically rewrite the url to a index.php, which process the url and depends on the method, then send response

but which is the properly way to process the url? this looks doen't look correct...

  1. get the uri and split it
  2. I should know what to do with each portion, eg. for GET /usr/1 I should do something like:

    if($myUri[0]=="usr")

    getUser($myUri[1]);

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 differe开发者_Python百科nt methods like getUsrByName($name) or getUsrByEmail($mail)


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

And:

domain.com/user/likes/StackOverflow/name/Kossel

Are not the same resource. Instead I'd do:

domain.com/user/?name=Kossel&likes=StackOverflow

This is what Stack Overflow uses:

stackoverflow.com/questions/tagged/php
stackoverflow.com/tags/php/new
stackoverflow.com/questions/tagged/mysql?sort=featured


To avoid long if/else statement, use variable function names. this allows you to use the url string to call the correct function.

http://php.net/manual/en/functions.variable-functions.php

Also, you may want to use classes/class methods instead of functions. this way you can set up an __autoload function, which will allow you to only load code that you are going to use each time the index.php is called.

MVC architecture usually breaks their urls into /class_name/class_method_name/arguments...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜