php 在 RESTful API 中使用干净的 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8291712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:22:14  来源:igfitidea点击:

Using Clean URLs in RESTful API

phprest

提问by Tyler Buchea

"Clean URLs" also known as "RESTful URLs" are user-friendly, purely structural, and do not contain a query string. Instead they contain only the path of the resource.

“干净的 URL”也称为“RESTful URL”是用户友好的、纯结构的,并且不包含查询字符串。相反,它们仅包含资源的路径。

ie: "http://twitter.com/users/show/"+username+".json"

即:“http://twitter.com/users/show/”+用户名+“.json”

Questions about server-side functionality:

关于服务器端功能的问题:

  1. Do I need to make a unique server-side API script for each directory?

  2. Can I forward all requests to just one script if so how do I pull useful information from the Clean URL structure ($_GET['url_structure'])?

  3. Why does twitter call to a .json file that surely doesn't exist. It must get generated on request. How does this work? This leads me to believe that the answer to question 2 is yes.

  1. 我是否需要为每个目录制作一个唯一的服务器端 API 脚本?

  2. 如果可以,我是否可以将所有请求仅转发到一个脚本,我该如何从 Clean URL 结构 ($_GET['url_structure']) 中提取有用的信息?

  3. 为什么 twitter 调用一个肯定不存在的 .json 文件。它必须根据要求生成。这是如何运作的?这让我相信问题 2 的答案是肯定的。

回答by Bailey Parker

1)Not if you use a RESTful framework like RecessPHPor if you use a mod_rewrite rule in your .htaccess file to redirect all API requests to a single PHP file (known as the front controller).

1)如果您使用像RecessPHP这样的 RESTful 框架,或者如果您在 .htaccess 文件中使用 mod_rewrite 规则将所有 API 请求重定向到单个 PHP 文件(称为前端控制器),则不会。

.htaccess

.htaccess

RewriteEngine On
RewriteRule ^/api/ api.php

api.php

api.php

$request = $_SERVER['REQUEST_URI'];  //this would be /users/show/abc.json


2)You can use the rewrite module of apache to redirect all api requests to a special PHP file that handles them. Depending on your apache configuration, the original requested (RESTful) url will be stored in a server variable in PHP, I believe it's $_SERVER['REQUEST_URI']. Of course you could also just pass along a $_GET[]variable to PHP that contained the RESTful url.

2)您可以使用 apache 的重写模块将所有 api 请求重定向到处理它们的特殊 PHP 文件。根据您的 apache 配置,原始请求的 (RESTful) url 将存储在 PHP 中的服务器变量中,我相信它是$_SERVER['REQUEST_URI']. 当然,您也可以将$_GET[]包含 RESTful url的变量传递给 PHP。

.htaccess

.htaccess

RewriteEngine On
RewriteRule ^/api/([^\.]+).(xml|json|atom) api.php?url=&type=

api.php

api.php

$request_parts = explode('/', $_GET['url']); // array('users', 'show', 'abc')
$file_type     = $_GET['type'];

$output = get_data_from_db(); //Do your processing here
                              //You can outsource to other files via an include/require

//Output based on request
switch($file_type) {
    case 'json':
        echo json_encode($output);
        break;
    case 'xml':
        echo xml_encode($output); //This isn't a real function, but you can make one
        break;
    default:
        echo $output;
}


3)Twitter (and many other APIs) use this because it is a convenient way of supplying the format that an application expects back from an API. All of the API requests are rerouted to a single PHP file which handles creating all the files and echoing their contents to the output. The file is never actually stored on the server (unless it is cached).

3)Twitter(和许多其他 API)使用它是因为它是一种提供应用程序期望从 API 返回的格式的便捷方式。所有 API 请求都重新路由到单个 PHP 文件,该文件处理创建所有文件并将其内容回显到输出。该文件实际上从未存储在服务器上(除非它被缓存)。



Good Resources

好资源



A note on RecessPHP. It's certainly a great tool and I would encourage you look at it (maybe at its source to get an idea of how it processes things), but that said, it seems a bit clunky to me. The fact that path names are written in special comments seems very not-PHP to me. I'd stray away from this, and I wouldn't call it the perfect framework, but it's certainly a start. Good luck!

关于 RecessPHP 的说明。它当然是一个很棒的工具,我鼓励您查看它(也许可以从它的源头了解它如何处理事物),但话虽如此,对我来说似乎有点笨拙。路径名写在特殊注释中的事实对我来说似乎非常不 PHP。我会偏离这一点,我不会称它为完美的框架,但这肯定是一个开始。祝你好运!

回答by PHPGuru

This worked for me: Put this in the htaccess file at the root of your website.

这对我有用:把它放在你网站根目录的 htaccess 文件中。

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule api/(.*)$ api/api.php?request= [QSA,NC,L]
RewriteRule (recipe/.*) api/app.php?request= [QSA,NC,L]
</IfModule>

And then if you go to the page http://localhost/api/person/susanYou will see that it takes you to the file at http://localhost/api/api.phpI also have a recipe page that I go to using http://localhost/recipe/edit/2Put this in the api.php file:

然后如果你转到页面http://localhost/api/person/susan你会看到它把你带到了http://localhost/api/api.php我还有一个食谱页面使用http://localhost/recipe/edit/2把它放在 api.php 文件中:

<?php
$requestParts = explode('/',$_GET['request']);
$category = $requestParts[0];
$action = $requestParts[1];
$data = $requestParts[2];
if($category == 'recipe'){
    include($_SERVER['DOCUMENT_ROOT'].'/pages/add_recipe.php');
}

The variables above will hold the category: recipe, action: add or edit, and the data which can be a number which is the id for the recipe or what ever you want it to be. Then inside the add_recipe.php use the variables to determine whether you are editing or adding a recipe. And if you use the api you can include different files depending on what ajax request you are using to talk to your api.

上面的变量将包含类别:recipe、action:add 或 edit,以及可以是数字的数据,即配方的 id 或您想要的任何内容。然后在 add_recipe.php 中使用变量来确定您是在编辑还是添加配方。如果您使用 api,您可以根据您用来与 api 对话的 ajax 请求包含不同的文件。

回答by Sony Choudhary

Try this:

尝试这个:

RewriteRule ^([^/]+)\/([^/]+)\/?$ getdata.php?para1=&para2= [NC]