2015.10 大三上 面向web的计算课程
在大三上的课程中,海涛老师要求项目中运用rest进行数据采集。我两眼懵逼,啥是rest呀?然后就去网上找了学习资料。然后之后就着手开始自己写一个rest api。为什么要自己写呢?因为我没用框架,第一次使用php做网站,我想先打好基础再考虑高层次的东西,就没有用框架。其他人用的诸如laravel之类的PHP框架自己本身会带rest机制。对于我一个没用框架的孩子,只能自己默默写了。
当然,有参考例子哦http://www.gen-x-design.com/archives/create-a-rest-api-with-php/,不过这个例子一点都不全面,我自己补充了很多。
<?php
class RestUtils
{
public static function processRequest()
{
// get our verb
$request_method = strtolower($_SERVER['REQUEST_METHOD']);
$return_obj = new RestRequest();
// we'll store our data here
$data = array();
switch ($request_method)
{
// gets are easy...
case 'get':
$data = $_GET;
break;
// so are posts
case 'post':
$data = $_POST;
break;
// here's the tricky bit...
case 'put':
case 'delete':
// basically, we read a string from PHP's special input location,
// and then parse it out into an array via parse_str... per the PHP docs:
// Parses str as if it were the query string passed via a URL and sets
// variables in the current scope.
$string=file_get_contents('php://input');
preg_match_all("|\".*\"|",$string,$out1, PREG_PATTERN_ORDER);
preg_match_all("|\"\s+.*\s+------|",$string,$out2, PREG_PATTERN_ORDER);
for($i=0;$i<count($out2[0]);$i++){
$out1[0][$i]=explode("\"", $out1[0][$i])[1];
$out2[0][$i]=explode("\n", $out2[0][$i])[2];
$out2[0][$i]=trim($out2[0][$i]);
}
$data=array();
for($i=0;$i<count($out2[0]);$i++){
$data[$out1[0][$i]] = $out2[0][$i];
}
break;
}
// store the method
$return_obj->setMethod($request_method);
// set the raw data, so we can access it if needed (there may be
// other pieces to your requests)
$return_obj->setRequestVars($data);
if(isset($data['data']))
{
// translate the JSON to an Object for use however you want
$return_obj->setData(json_decode($data['data']));
}
return $return_obj;
}
public static function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . RestUtils::getStatusCodeMessage($status);
// set the status
header($status_header);
// set the content type
header('Content-type: ' . $content_type);
// pages with body are easy