在 PHP 中创建一个 RESTful API? [英] Create a RESTful API in PHP?

查看:47
本文介绍了在 PHP 中创建一个 RESTful API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个非常快速和简单的 PHP 应用程序,用于从 XML 文件中读取分类广告并允许用户对其执行 CRUD 操作(这是一项家庭作业).

I developed a very quick and simple PHP application for reading classified ads from an XML file and allowing the user to perform CRUD operations on it (this was a homework assignment).

我现在的任务是将此应用程序开发为 RESTful 服务.这位教授实际上似乎对 RESTful 服务没有任何经验,因为他说我的应用程序被发现要提交给下一个作业,而我的研究表明它并没有真正满足所有 RESTful 要求.

I'm now tasked with developing this application to a RESTful service. The professor actually doesn't seem to have any experience with RESTful services, because he said my application was find to hand in for the next assignment, when my research indicates it doesn't really fulfil all the RESTful requirements.

无论如何,为了学习目的,我想正确地做到这一点,即使我可以交出我的旧作业并取得好成绩.不过,我在学习从哪里开始时遇到了麻烦;我不确定 RESTful 服务到底是什么.

Regardless, I want to do this correctly for learning purposes, even if I can hand in my old assignment and get a good grade. I'm having trouble learning where to begin though; I'm not sure exactly what a RESTful service really is.

我认为获得建议的最佳方式是发布我之前作业中的示例代码,看看我是如何处理事情的,以及我需要如何处理事情.

I think the best way to get advice is to post sample code from my previous assignment to see how I handled things and how I need to handle things instead.

例如,这是我创建新分类广告的方法.

For instance, here is how I create new classifieds.

创建.php

//Basically just a list of <INPUT TYPE = "text" NAME = "something"> in the <body> fields

CreateSuccess.php

<html><head><?php $simplerXML = simplexml_load_file('file.xml'); 
//Generate the basic ad information
$newAd = $simplerXML->addChild('advertisement','');
$newAd->addAttribute('category', $_POST["category"]);
$title = $newAd->addChild('title', $_POST["title"]);
$title->addAttribute('ID', $_POST["ID"]);
$pageTitle = $newAd->addChild('pagetitle', $_POST["pagetitle"]);
//etc, for all the SUBMIT boxes

//save the XML
$simplerXML->asXML('file.xml');
echo "<script type='text/javascript'>
//redirect back to ad listing page
window.onload = function () { top.location.href = 'ads.php'; };
</script>";
?></head>
<body></body></html>

我还在 RUD 操作中使用 URL 参数.我听说也不允许使用网址参数?

I'm also using URL parameters for the RUD actions. I've heard URL parameters are not allowed as well?

谢谢.

那么 SWITCH 语句是否在 index.php 文件中?然后每个case都会调用一个函数,即POST方法的CreateXML?那么它需要的参数是对象类型、对象id、内容类型?如何获取用于更新 XML 的值,是否只需将其发送到包含输入框列表的 Create.php 文件?

So the SWITCH statement, does it go in the index.php file? And then each case will call a function, ie CreateXML for the POST method? Then the parameters it needs will be the object type, object id, and content type? How do I get the values to update the XML with, do I just send it to the Create.php file containing the list of input boxes?

推荐答案

如果您的服务支持所有 CRUD 操作,则始终建议实现 RESTful 接口.这样做并不难.我在下面概述了一些基础知识.

If your service supports all CRUD operations, it's always advisable to implement a RESTful interface. It's not super-hard to do so. I've outlined some of the basics below.

RESTful 服务只做几件事:

A RESTful service simply does a few things:

  1. 它使用 HTTP 请求方法进行 CRUD 操作的通信
  2. 它使用 HTTP 状态代码来传达响应状态,并且
  3. 它使用 URI 来定义您的资源(文件、您正在访问的数据库项目等).
  4. 它是无状态的

我们的想法是尽量减少为 HTTP 规范中已经定义的这些内容开发自定义通信.

The idea is to minimize the development of custom communications for these things that are already defined in the HTTP spec.

1 - 请求方法

支持 RESTful 服务所需的 4 种 HTTP 请求方法是:

The 4 HTTP request methods you're required to support for a RESTful service are:

  1. 发布
  2. 获取
  3. 放置
  4. 删除

并且您可以选择支持

  1. 补丁
  2. 头部

您可以将这些直接映射到您的 CRUD 操作,如下所示:

You can map these directly to your CRUD actions as follows:

  • POST = 创建
  • GET = 检索
  • PUT = 更新
  • DELETE = 删除
  • PATCH = 编辑(部分更新,例如更改密码".PUT 变为替换")
  • HEAD = 仅标题(有关资源的元数据)

为此,请使用简单的请求方法路由器正确路由请求,如下所示:

To do this, route requests properly with a simple request method router as follows:

switch ($_SERVER["REQUEST_METHOD"]) {
    case "POST":
        // Create action
        break;
    case "GET":
        // Retrieve action
        break;
    case "PUT":
        // Update action
        break;
    case "DELETE":
        // Delete action
        break;
}

<小时>

2 - 状态代码您应该进一步从您的服务中实现 HTTP 状态代码,以将状态传达回客户端,例如:


2 - STATUS CODE You should further implement HTTP status codes from your service to communicate status back to the client, e.g.:

  • 20 倍 = 成功
  • 30x = 重定向
  • 40x = 沟通问题
  • 50x = 服务器错误

为此,只需在您的响应前面加上正确的 HTTP 标头输出,例如:

To do this, simply prepend your response with the proper HTTP header output, e.g.:

header("Status: 500 Internal Server Error");

您可以在此处参考已实现的 HTTP 状态代码的完整列表:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

You can reference the full list of implemented HTTP status codes here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

3 - URI对于 URI,RESTful 服务通常遵循自顶向下的方法进行分类命名,例如

3 - URIs For URIs, RESTful services usually follow a top-down approach to categorized naming, e.g.

/object_type/id.content_type

示例:

POST /user
PUT /user/1
GET /user/1.json
GET /user/1.html

您可以使用 Apache 和 .htaccess 文件中的 mod_rewrite 为上述约定实现一个非常基本的 RESTful 路由器,如下所示:

You can implement a very rudimentary RESTful router for the above convention using Apache with mod_rewrite in an .htaccess file, as follows:

RewriteEngine On
RewriteRule ^([^\/]+)\/([^\.]+)\.(\w+)$  index.php?object_type=$1&object_id=$2&content_type=$3

然后您将有 index.php 寻找适当的 object_type 和 id 以进行适当的路由,例如:

You would then have index.php Look for the appropriate object_type and id to route appropriately, e.g.:

$object = $_GET["object_type"];
$id = (int) $_GET["object_id"];
$content_type = $_GET["content_type"];

// Route from here to a class with the name of the object (e.g. UserController) via __autoload
// or to a file (e.g. user.php) via include, and pass id and content_type as params

<小时>

4 - 无状态简单地说,服务器不为客户端维护状态".无需存储会话或状态.每个请求代表一个完整的事务.IE.如果我 GET user/1,服务器不会记住我这样做了,并且未来的请求不会依赖或受以前的影响.


4 - STATELESSNESS Simply stated, the server maintains no "state" for the client. No requirements for storing session or status. Each request represents a complete transaction. I.e. if I GET user/1, the server won't remember that I did that, and future requests won't be dependent upon or affected by previous ones.

如果你实现了这些标准,恭喜你,你已经构建了一个 RESTful 服务!

If you implement these standards, congrats, you've built a RESTful service!

这篇关于在 PHP 中创建一个 RESTful API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆