admin 发表于 2023-2-16 18:54:44

PHP RESTful

<div id="article_content" class="article_content clearfix">
      <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
      <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-6e43165c0a.css">
                <div id="content_views" class="htmledit_views">
                  <p>REST&#xff08;英文&#xff1a;Representational State Transfer&#xff0c;简称REST) &#xff0c;指的是一组架构约束条件和原则。</p>
<p>符合REST设计风格的Web API称为RESTful API。它从以下三个方面资源进行定义&#xff1a;</p>
<ul><li>直观简短的资源地址&#xff1a;URI&#xff0c;比如&#xff1a;<code>http://example.com/resources/</code>。</li><li>传输的资源&#xff1a;Web服务接受与返回的互联网媒体类型&#xff0c;比如&#xff1a;JSON&#xff0c;XML&#xff0c;YAM等。</li><li>对资源的操作&#xff1a;Web服务在该资源上所支持的一系列请求方法&#xff08;比如&#xff1a;POST&#xff0c;GET&#xff0c;PUT或DELETE&#xff09;。</li></ul>
<p>本教程我们将使用 PHP(不用框架) 来创建一个 RESTful web service&#xff0c;在文章末尾你可以下载本章节使用到的代码。</p>
<p>通过本教程你将学习到以下内容&#xff1a;</p>
<ul><li>创建一个 RESTful Webservice。</li><li>使用原生 PHP, 不依赖任何框架。</li><li>URI 模式需要遵循 REST 规则。</li><li>RESTful service 接受与返回的格式可以是 JSON, XML等。</li><li>根据不同情况响应对应的 HTTP 状态码。</li><li>演示请求头的使用。</li><li>使用 REST 客户端来测试 RESTful web service。</li></ul>
<hr>
<h2>RESTful Webservice 实例</h2>
<p>以下代码是 RESTful 服务类 <strong>Site.php</strong>&#xff1a;</p>
<h2>实例</h2>
<p><?php /* * 菜鸟教程 RESTful 演示实例 * RESTful 服务类 */ Class Site { private $sites &#61; array( 1 &#61;> 'TaoBao', 2 &#61;> 'Google', 3 &#61;> 'Runoob', 4 &#61;> 'Baidu', 5 &#61;> 'Weibo', 6 &#61;> 'Sina' ); public function getAllSite(){ return $this->sites; } public function getSite($id){ $site &#61; array($id &#61;> ($this->sites[$id]) ? $this->sites[$id] : $this->sites); return $site; } } ?></p>
<hr>
<h2>RESTful Services URI 映射</h2>
<p>RESTful Services URI 应该设置为一个直观简短的资源地址。Apache 服务器的 .htaccess 应设置好对应的 Rewrite 规则。</p>
<p>本实例我们将使用两个 URI 规则&#xff1a;</p>
<p>1、获取所有站点列表&#xff1a;</p>
<pre>http://localhost/restexample/site/list/</pre>
<p>2、使用 id 获取指定的站点&#xff0c;以下 URI 为获取 id 为 3 的站点&#xff1a;</p>
<pre>http://localhost/restexample/site/list/3/</pre>
<p>项目的 <strong>.htaccess</strong> 文件配置规则如下所示&#xff1a;</p>
<pre># 开启 rewrite 功能
Options &#43;FollowSymlinks
RewriteEngine on

# 重写规则
RewriteRule ^site/list/$   RestController.php?view&#61;all
RewriteRule ^site/list/(&#43;)/$   RestController.php?view&#61;single&id&#61;$1 </pre>
<hr>
<h2>RESTful Web Service 控制器</h2>
<p>在 <strong>.htaccess</strong> 文件中&#xff0c;我们通过设置参数 'view' 来获取 RestController.php 文件中对应的请求&#xff0c;通过获取 'view' 不同的参数来分发到不同的方法上。<strong>RestController.php </strong>文件代码如下&#xff1a;</p>
<h2>实例</h2>
<p><?php require_once(&#34;SiteRestHandler.php&#34;); $view &#61; &#34;&#34;; if(isset($_GET[&#34;view&#34;])) $view &#61; $_GET[&#34;view&#34;]; /* * RESTful service 控制器 * URL 映射 */ switch($view){ case &#34;all&#34;: // 处理 REST Url /site/list/ $siteRestHandler &#61; new SiteRestHandler(); $siteRestHandler->getAllSites(); break; case &#34;single&#34;: // 处理 REST Url /site/show/<id>/ $siteRestHandler &#61; new SiteRestHandler(); $siteRestHandler->getSite($_GET[&#34;id&#34;]); break; case &#34;&#34; : //404 - not found; break; } ?></p>
<h3>简单的 RESTful 基础类</h3>
<p>以下提供了 RESTful 的一个基类&#xff0c;用于处理响应请求的 HTTP 状态码&#xff0c;<strong>SimpleRest.php</strong> 文件代码如下&#xff1a;</p>
<h2>实例</h2>
<p><?php /* * 一个简单的 RESTful web services 基类 * 我们可以基于这个类来扩展需求 */ class SimpleRest { private $httpVersion &#61; &#34;HTTP/1.1&#34;; public function setHttpHeaders($contentType, $statusCode){ $statusMessage &#61; $this -> getHttpStatusMessage($statusCode); header($this->httpVersion. &#34; &#34;. $statusCode .&#34; &#34;. $statusMessage); header(&#34;Content-Type:&#34;. $contentType); } public function getHttpStatusMessage($statusCode){ $httpStatus &#61; array( 100 &#61;> 'Continue', 101 &#61;> 'Switching Protocols', 200 &#61;> 'OK', 201 &#61;> 'Created', 202 &#61;> 'Accepted', 203 &#61;> 'Non-Authoritative Information', 204 &#61;> 'No Content', 205 &#61;> 'Reset Content', 206 &#61;> 'Partial Content', 300 &#61;> 'Multiple Choices', 301 &#61;> 'Moved Permanently', 302 &#61;> 'Found', 303 &#61;> 'See Other', 304 &#61;> 'Not Modified', 305 &#61;> 'Use Proxy', 306 &#61;> '(Unused)', 307 &#61;> 'Temporary Redirect', 400 &#61;> 'Bad Request', 401 &#61;> 'Unauthorized', 402 &#61;> 'Payment Required', 403 &#61;> 'Forbidden', 404 &#61;> 'Not Found', 405 &#61;> 'Method Not Allowed', 406 &#61;> 'Not Acceptable', 407 &#61;> 'Proxy Authentication Required', 408 &#61;> 'Request Timeout', 409 &#61;> 'Conflict', 410 &#61;> 'Gone', 411 &#61;> 'Length Required', 412 &#61;> 'Precondition Failed', 413 &#61;> 'Request Entity Too Large', 414 &#61;> 'Request-URI Too Long', 415 &#61;> 'Unsupported Media Type', 416 &#61;> 'Requested Range Not Satisfiable', 417 &#61;> 'Expectation Failed', 500 &#61;> 'Internal Server Error', 501 &#61;> 'Not Implemented', 502 &#61;> 'Bad Gateway', 503 &#61;> 'Service Unavailable', 504 &#61;> 'Gateway Timeout', 505 &#61;> 'HTTP Version Not Supported'); return ($httpStatus[$statusCode]) ? $httpStatus[$statusCode] : $status; } } ?></p>
<h3>RESTful Web Service 处理类</h3>
<p>以下是一个 RESTful Web Service 处理类 SiteRestHandler.php&#xff0c;继承了上面我们提供的 RESTful 基类&#xff0c;类中通过判断请求的参数来决定返回的 HTTP 状态码及数据格式&#xff0c;实例中我们提供了三种数据格式&#xff1a; &#34;application/json&#34; 、 &#34;application/xml&#34; 或 &#34;text/html&#34;&#xff1a;</p>
<p><strong>SiteRestHandler.php</strong> 文件代码如下:</p>
<h2>实例</h2>
<p><?php require_once(&#34;SimpleRest.php&#34;); require_once(&#34;Site.php&#34;); class SiteRestHandler extends SimpleRest { function getAllSites() { $site &#61; new Site(); $rawData &#61; $site->getAllSite(); if(empty($rawData)) { $statusCode &#61; 404; $rawData &#61; array('error' &#61;> 'No sites found!'); } else { $statusCode &#61; 200; } $requestContentType &#61; $_SERVER['HTTP_ACCEPT']; $this ->setHttpHeaders($requestContentType, $statusCode); if(strpos($requestContentType,'application/json') !&#61;&#61; false){ $response &#61; $this->encodeJson($rawData); echo $response; } else if(strpos($requestContentType,'text/html') !&#61;&#61; false){ $response &#61; $this->encodeHtml($rawData); echo $response; } else if(strpos($requestContentType,'application/xml') !&#61;&#61; false){ $response &#61; $this->encodeXml($rawData); echo $response; } } public function encodeHtml($responseData) { $htmlResponse &#61; &#34;<table border&#61;'1'>&#34;; foreach($responseData as $key&#61;>$value) { $htmlResponse .&#61; &#34;<tr><td>&#34;. $key. &#34;</td><td>&#34;. $value. &#34;</td></tr>&#34;; } $htmlResponse .&#61; &#34;</table>&#34;; return $htmlResponse; } public function encodeJson($responseData) { $jsonResponse &#61; json_encode($responseData); return $jsonResponse; } public function encodeXml($responseData) { // 创建 SimpleXMLElement 对象 $xml &#61; new SimpleXMLElement('<?xml version&#61;&#34;1.0&#34;?><site></site>'); foreach($responseData as $key&#61;>$value) { $xml->addChild($key, $value); } return $xml->asXML(); } public function getSite($id) { $site &#61; new Site(); $rawData &#61; $site->getSite($id); if(empty($rawData)) { $statusCode &#61; 404; $rawData &#61; array('error' &#61;> 'No sites found!'); } else { $statusCode &#61; 200; } $requestContentType &#61; $_SERVER['HTTP_ACCEPT']; $this ->setHttpHeaders($requestContentType, $statusCode); if(strpos($requestContentType,'application/json') !&#61;&#61; false){ $response &#61; $this->encodeJson($rawData); echo $response; } else if(strpos($requestContentType,'text/html') !&#61;&#61; false){ $response &#61; $this->encodeHtml($rawData); echo $response; } else if(strpos($requestContentType,'application/xml') !&#61;&#61; false){ $response &#61; $this->encodeXml($rawData); echo $response; } } } ?></p>
<p>接下来我们通过 http://localhost/restexample/site/list/ 访问&#xff0c;输出结果如下&#xff1a;</p>
<p style="text-align:center;"></p>
<hr>
<h2>RESTful Web Service 客户端</h2>
<p>接下来我们可以使用 Google Chrome 浏览器的 &#34;Advance Rest Client&#34; 作为 RESTful Web Service 客户端来请求我们的服务。</p>
<p>实例中请求 http://localhost/restexample/site/list/ 地址&#xff0c;接收数据类似为 <strong>Accept: application/json</strong></p>
<div style="text-align:center;">

</div>
<p>请求 id 为 3 的站点 Runoob(菜鸟教程)&#xff0c;访问地址为 http://localhost/restexample/site/list/3/&#xff0c;</p>
<p style="text-align:center;"></p>
<h3>源码下载</h3>
<p>实例中使用到的代码可点击以下按钮下载&#xff1a;</p>
<p><ahref="http://static.runoob.com/download/restexample.zip">源码下载</a></p>
                </div>
      </div>
      <div id="treeSkill"></div>
页: [1]
查看完整版本: PHP RESTful