- 论坛徽章:
- 0
|
Php代码
- 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':
- // 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.
- parse_str(file_get_contents('php://input'), $put_vars);
- $data = $put_vars;
- 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;
- }
复制代码 Like I said, pretty straight-forward. However, a few things to note… First, you typically don’t accept data for DELETE requests, so we don’t have a case for them in the switch. Second, you’ll notice that we store both the request variables, and the parsed JSON data. This is useful as you may have other stuff as a part of your request (say an API key or something) that isn’t truly the data itself (like a new user’s name, email, etc.).
正如我刚才所说的,非常的简单直接高效。然后,有几点需要注意:首先,我们不接受DELETE请求,因此我们在switch中不提供相应的case条件。其次,你会注意到我们把请求参数和解析后的JSON数据都存储起来了,这在请求中有其他需要处理的数据时会变得非常有用(API key或者其他),这些并不是请求的数据本身(比如一个新用户的名字、电子邮箱等)。
So, how would we use this? Let’s go back to the user example. Assuming you’ve routed your request to the correct controller for users, we could have some code like this:
那么,我们如何使用它呢?让我们回到刚才user的例子。假设你已经通过路由把请求对应到正确的users控制器,代码如下:
Php代码
- $data = RestUtils::processRequest();
- switch($data->getMethod){
- case 'get':
- // retrieve a list of users
- break;
- case 'post':
- $user = new User();
- $user->setFirstName($data->getData()->first_name); // just for example, this should be done cleaner
- // and so on...
- $user->save();
- break;
- // etc, etc, etc...
- }
复制代码 Please don’t do this in a real app, this is just a quick-and-dirty example. You’d want to wrap this up in a nice control structure with everything abstracted properly, but this should help you get an idea of how to use this stuff. But I digress, let’s move on to sending a response.
Sending the Response
请不要在真实的应用中这样做,这是一个非常快速和不干净的示例。你应该使用一个设计良好的控制结构来把它包裹起来,适当的抽象化,但是这样有助于你理解如何使用这些东西。让我们继续代码,发送一个响应信息。
Now that we can interpret the request, let’s move on to sending the response. We already know that all we really need to do is send the correct status code, and maybe some body (if this were a GET request, for example), but there is an important catch to responses that have no body. Say somebody made a request against our sample user API for a user that doesn’t exist (i.e. api/user/123). The appropriate status code to send is a 404 in this case, but simply sending the status code in the headers isn’t enough. If you viewed that page in your web browser, you would get a blank screen. This is because Apache (or whatever your web server runs on) isn’t sending the status code, so there’s no status page. We’ll need to take this into account when we build out our function. Keeping all that in mind, here’s what the code should look like:
既然我们已经可以解析请求,那么接下来我们继续来发送一个响应。我们已经知道我们真正需要去做的是发送一个正确的状态码和一些响应消息体(例如这是一个GET请求),但是对于没有消息体的响应来说有一个重要的catch(译者:不好意思,实在是不知道如何翻译这个词)。假定某个人向我们的user接口发送一个请求某个用户信息的请求,而这个用户却不存在(比如:api/user/123),此时系统发送最合适的状态码是404。但是简单的在头信息中发送状态码是不够的,如果你通过网页浏览器浏览该页面,你会看到一个空白页面。这是因为apache服务器(或者其他服务器)并不会发送此状态码,因此没有状态页面。我们需要在构建方法的时候考虑到这一点。把所有的东西都考虑进去,代码会类似于下面这样:
Php代码
- 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
- if($body != ''){
- // send the body
- echo $body;
- exit;
- }
- // we need to create the body if none is passed
- else
- {
- // create some body messages
- $message = '';
- // this is purely optional, but makes the pages a little nicer to read
- // for your users. Since you won't likely send a lot of different status codes,
- // this also shouldn't be too ponderous to maintain
- switch($status) {
- case 401:
- $message = 'You must be authorized to view this page.';
- break;
- case 404:
- $message = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';
- break;
- case 500:
- $message = 'The server encountered an error processing your request.';
- break;
- case 501:
- $message = 'The requested method is not implemented.';
- break;
- }
- // servers don't always have a signature turned on (this is an apache directive "ServerSignature On")
- $signature = ($_SERVER['SERVER_SIGNATURE'] == '') ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];
- // this should be templatized in a real-world solution
- $body = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>' . $status . ' ' . RestUtils::getStatusCodeMessage($status) . '</title>
- </head>
- <body>
- <h1>' . RestUtils::getStatusCodeMessage($status) . '</h1>
- ' . $message . '
- <hr />
- <address>' . $signature . '</address>
- </body>
- </html>';
- echo $body;
- exit;
- }
- }
复制代码 That’s It! We technically have everything we need now to process requests and send responses. Let’s talk a bit more about why we need to have a standard body response or a custom one. For GET requests, this is pretty obvious, we need to send XML / JSON content instead of a status page (provided the request was valid). However, there’s also POSTs to deal with. Inside of your apps, when you create a new entity, you probably fetch the new entity’s ID via something like mysql_insert_id(). Well, if a user posts to your API, they’ll probably want that new ID as well. What I’ll usually do in this case is simply send the new ID as the body (with a 201 status code), but you could also wrap that in XML or JSON if you’d like.
就这样,从技术上来说,我们已经具备了处理请求和发送响应的所有东西。下面我们再讨论以下为什么我们需要一个标准的相应提或者一个自定义的。对于GET请求来说,非常明显,我们需要发送XML/JSON内容而不是一个状态页(假设请求是合法的)。然后,我们还有POST请求要去处理。在你的应用内部,当你创建一个新的实体,你也许需要使用通过类似于mysql_insert_id()这样的函数得到这个实体的ID。那么,当一个用户提交到你的接口,他们将很可能想要知道这个新的ID是什么。在这种情况下,我通常的做法是非常简单的把这个新ID作为响应的消息体发送给用户(同时发送一个201的状态码头信息),但是如果你愿意,你也可以使用XML或者JSON来把它包裹起来。
So, let’s extend our sample implementation a bit:
现在,让我们来扩展一下我们的例子,让它更加实际一点:
Php代码
- switch($data->getMethod){
- // this is a request for all users, not one in particular
- case 'get':
- $user_list = getUserList(); // assume this returns an array
- if($data->getHttpAccept == 'json'){
- RestUtils::sendResponse(200, json_encode($user_list), 'application/json');
- }else if ($data->getHttpAccept == 'xml') {
- // using the XML_SERIALIZER Pear Package
- $options = array
- (
- 'indent' => ' ',
- 'addDecl' => false,
- 'rootName' => $fc->getAction(),
- XML_SERIALIZER_OPTION_RETURN_RESULT => true
- );
- $serializer = new XML_Serializer($options);
- RestUtils::sendResponse(200, $serializer->serialize($user_list), 'application/xml');
- }
- break;
- // new user create
- case 'post':
- $user = new User();
- $user->setFirstName($data->getData()->first_name); // just for example, this should be done cleaner
- // and so on...
- $user->save();
- // just send the new ID as the body
- RestUtils::sendResponse(201, $user->getId());
- break;
- }
复制代码 |
|