这里的 Neville K 的回答是我公司如何处理 RESTful api 调用的示例。
首先,我们有一个使用 switch 语句处理调用的 php 文件。将不同的操作路由到所述函数和类。
/* Class file that is called on this page */
include_once "$_SERVER[DOCUMENT_ROOT]/classes/class.myclass.php";
/**
* This function makes it simpler to stop it from working for debugging purposes.
* All we have to do is comment out the one line of code apiCall($_REQUEST);
* You could have this outside of the function and it would work just as well.
* @param type $REQUEST
*/
function apiCall($REQUEST) {
$con = new MyClass();
switch ($REQUEST['action']) {
case 'getList':
/* Setting the content type to json means that the developer can
* expect a response in the form of parseable json.
*/
header('Content-Type: application/json');
echo json_encode($con->getList($REQUEST));
case 'setValue':
header('Content-Type: application/json');
echo json_encode($con->setValue($REQUEST));
case 'login':
if ($con->login($REQUEST)) {
header('Location: /index.php');
} else {
header('Content-Type: /login.php?status=Failed+Login');
}
default:
header('Content-Type: application/json');
/* If an invalid action was sent in, then this error message will be sent
* back to the user
*/
echo json_encode(['status' => 'Invalid API Call']);
}
}
/* Using $_REQUEST allows developers to access the api via GET or POST */
apiCall($_REQUEST);
然后我们处理我们调用的不同类中的所有逻辑。
class MyClass {
public function getList($REQUEST) {
$id = $REQUEST['id'];
/* code */
return ['status' => 'ok', 'results' => $array];
}
public function setList($REQUEST) {
/* code */
return ['status' => 'ok'];
}
public function login($REQUEST) {
/* code */
$_SESSION['user_id'] = $user_id;
return $login_successful;
}
}
使用JSON 非常适合通过AJAX 调用发送信息的应用程序。使用header('Location:') 非常适合在没有ajax 的情况下提交表单。
然后,您可以使用 JavaScript ajax 调用或根据您处理数据提交的方式进行提交。
jQuery.getJSON使用示例
$.getJSON('/switch.php', $.param({id: id, action: 'getList'}), function (json) {
if (json) {
/*code*/
}
});
然后,您会将一个带有操作的隐藏输入传递到切换页面以进行常规表单提交。
<form action="/switch.php" method="post">
<!--hidden input named action to direct which switch to use-->
<input name="action" value="login" type="hidden"/>
<input name="username"/>
<input name="password" type="password"/>
<input type="submit"/>
</form>
这些示例适用于 html/JavaScript Web 应用程序。如果您使用的是 JAVA、Python、.NET 或其他一些语言,它就像使用 REST API 并解析 JSON 以找出如何处理您的应用程序逻辑一样简单。
您甚至可以使用 file_get_contents 或 curl 运行 php 到 php api 调用。
$data = [
'action' => 'setValue',
'information' => 'More'
];
$json = json_decode(file_get_contents('/switch.php?' . http_build_query($data)),true);
if(!empty($json)){
/*code*/
}
您可以为每个调用创建一个单独的页面,而不必担心将action 传递给每个请求。但是你的文件树开始看起来像这样。
/api/loginSubmit.php
/api/login.php
/api/getListFromId.php
/api/getList.php
/api/setValues.php
/api/getValues.php
遍历所有这些文件以找出问题所在真的很乏味。