jalbam / fake_rest_server
用PHP编写的简单易配置的REST服务器。
Requires
- php: >=4.0.0
This package is not auto-updated.
Last update: 2024-09-27 23:15:15 UTC
README
作者:Joan Alba Maldonado (joanalbamaldonadoNO_SPAM_PLEASE AT gmail DOT com,请勿使用NO_SPAM_PLEASE)
用PHP编写的简单易配置的REST服务器。
版本:无版本
- 日期:2016年5月12日(大约)
描述
用PHP编写的简单易配置的REST服务器。
我制作它只是为了快速创建不同的REST服务器进行测试。
配置服务器
要添加新路径(路由)和方法,开发者只需创建一个表示路由的新文件夹结构(如果需要,包括文件夹和子文件夹),然后在其中一个名为 [method_desired].php 的文件中创建一个文件(例如,put.php)。
要开始开发您的REST服务器,您只需下载 src/ 文件夹中的文件。
您可以查看 src/_code/functions.php 文件(引擎将自动包含它),因为它提供了一些基本但有用的函数。在那里您也可以添加新函数或修改现有函数。
如果您想添加数据,可以使用 src/_code/data/data.php 文件(引擎将自动包含它)。
如果您想添加配置数据,可以使用 src/_code/config.php 文件(引擎将自动包含它)。
因为引擎定义了 USING_REST_SERVER 常量,所以您可以在文件开头使用以下行来保护任何文件
<?php if (!defined("USING_REST_SERVER") || !USING_REST_SERVER) { return; } ?>
注意:上述授权代码也定义在 AUTHORIZATION_CODE 常量中(位于 src/_code/config.php 文件内)。
示例
-
在根文件夹中(其中包含 src/_code/ 文件夹和 src/index.php 文件),创建一个名为 myRESTService/ 的文件夹。
-
在刚刚创建的 myRESTService/ 文件夹内,创建另一个名为 user/ 的文件夹,并在其中创建两个文件:index.php 和 get.php。
-
在 myRESTService/user/index.php 文件中放置以下代码
<?php //Users info (this could be in the "src/_code/config.php" file, but it is just an example): $usersData = Array ( //User IDs: "1" => Array ( "name" => "John Doe", "favouriteFood" => "meat" ), "2" => Array ( "name" => "Joan Alba Maldonado", "favouriteFood" => "pizza" ) ); //Gets the data needed which has been sent through the REST client: $userId = getVariable("id"); //"getVariable" and other functions available in the "src/_code/functions.php" file.
- 在 myRESTService/user/get.php 文件中放置以下代码
<?php if ($userId === "") { echo "No id sent!"; } else if (array_key_exists($userId, $usersData)) { echo $usersData[$userId]["name"] . " likes eating " . $usersData[$userId]["favouriteFood"]; } else { echo "User cannot be found! (id=" . $userId . ")"; }
- 这样,我们将有一个配置好的REST服务器,使用 myRESTService/user/ 路由,接受带有 id 参数的 GET 方法。此示例可在 example_easy/ 文件夹中找到。
测试服务器
如果您没有REST客户端,可以通过在URL中添加debug=1参数以及所需的method参数(如果方法是GET则不需要)来在任意网页浏览器上测试服务器,例如:https:///fake_rest_server/src/index.php/route_1/subroute?method=post&debug=1&username=Joan
按照上面的示例,您可以使用网页浏览器访问以下链接
https:///route_to_the_REST_server/index.php/myRESTService/user/?method=get&debug=1&id=1(应该显示"John Doe喜欢吃肉")
https:///route_to_the_REST_server/index.php/myRESTService/user/?method=get&debug=1&id=2(应该显示"Joan Alba Maldonado喜欢吃披萨")
https:///route_to_the_REST_server/index.php/myRESTService/user/?method=get&debug=1&id=3(应该显示"用户未找到! (id=3)")
https:///route_to_the_REST_server/index.php/myRESTService/user/?method=get&debug=1(应该显示"未发送id!")
请注意,路由末尾的"/"字符是可选的。
最终评论
使用PHP语言扩展非常容易。项目已包含一些示例,包括路由、方法、函数和数据,例如用户账户等(位于example/和example_easy/文件夹中),但它们可以被删除。
唯一真正需要的代码位于src/文件夹中。在该文件夹内部,route_1/文件夹及其所有内容也可以被删除,因为它们只是示例。
许可证
此项目可免费用于任何非商业目的的复制、传播和修改,但必须保留作者名称和版权条款。除此之外,您可以根据意愿使用此项目,但绝不能出售它!