php不支持restful_php - 如何构建RESTful API?

这是一个简单的PHP中一个非常简单的例子。

有两个文件client.php&api.php。 我将两个文件放在同一个网址:http://localhost:8888/,因此您必须将链接更改为您自己的网址。 (该文件可以位于两个不同的服务器上)。

这只是一个例子,它非常快速和肮脏,而且自从我完成php以来已经很长时间了。 但这是api的想法。

client.php

/*** this is the client ***/

if (isset($_GET["action"]) && isset($_GET["id"]) && $_GET["action"] == "get_user") // if the get parameter action is get_user and if the id is set, call the api to get the user information

{

$user_info = file_get_contents('http://localhost:8888/api.php?action=get_user&id=' . $_GET["id"]);

$user_info = json_decode($user_info, true);

// THAT IS VERY QUICK AND DIRTY !!!!!

?>

Name: <?php echo $user_info["last_name"] ?>
First Name: <?php echo $user_info["first_name"] ?>
Age: <?php echo $user_info["age"] ?>

Return to the user list

}

else // else take the user list

{

$user_list = file_get_contents('http://localhost:8888/api.php?action=get_user_list');

$user_list = json_decode($user_list, true);

// THAT IS VERY QUICK AND DIRTY !!!!!

?>

}

?>

api.php

// This is the API to possibility show the user list, and show a specific user by action.

function get_user_by_id($id)

{

$user_info = array();

// make a call in db.

switch ($id){

case 1:

$user_info = array("first_name" => "Marc", "last_name" => "Simon", "age" => 21); // let's say first_name, last_name, age

break;

case 2:

$user_info = array("first_name" => "Frederic", "last_name" => "Zannetie", "age" => 24);

break;

case 3:

$user_info = array("first_name" => "Laure", "last_name" => "Carbonnel", "age" => 45);

break;

}

return $user_info;

}

function get_user_list()

{

$user_list = array(array("id" => 1, "name" => "Simon"), array("id" => 2, "name" => "Zannetie"), array("id" => 3, "name" => "Carbonnel")); // call in db, here I make a list of 3 users.

return $user_list;

}

$possible_url = array("get_user_list", "get_user");

$value = "An error has occurred";

if (isset($_GET["action"]) && in_array($_GET["action"], $possible_url))

{

switch ($_GET["action"])

{

case "get_user_list":

$value = get_user_list();

break;

case "get_user":

if (isset($_GET["id"]))

$value = get_user_by_id($_GET["id"]);

else

$value = "Missing argument";

break;

}

}

exit(json_encode($value));

?>

我没有为这个例子调用数据库,但通常这就是你应该做的。 您还应该用“curl”替换“file_get_contents”函数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值