首页 php框架 ThinkPHP thinkphp5.0极速搭建restful风格接口层(实例解析)

thinkphp5.0极速搭建restful风格接口层(实例解析)

Jun 20, 2020 pm 01:44 PM
restful thinkphp

下面由thinkphp框架教程栏目给大家介绍thinkphp5.0极速搭建restful风格接口层实例,希望对需要的朋友有所帮助!

thinkphp5.0极速搭建restful风格接口层(实例解析)

下面是基于ThinkPHP V5.0 RC4框架,以restful风格完成的新闻查询(get)、新闻增加(post)、新闻修改(put)、新闻删除(delete)等server接口层。

1、下载ThinkPHP V5.0 RC4版本;

2、配置虚拟域名(非必须,只是为了方便);

Apache\conf\extra\httpd-vhosts.conf

<VirtualHost *:80>
    DocumentRoot "D:/webroot/tp5/public"
    ServerName www.tp5-restful.com
    <Directory "D:/webroot/tp5/public">
	DirectoryIndex index.html index.php 
	AllowOverride All
	Order deny,allow
	Allow from all
	</Directory>
</VirtualHost>
登录后复制

3、开启伪静态支持.htaccess文件

apache方法:

a)在conf目录下httpd.conf中找到下面这行并去掉#

LoadModule rewrite_module modules/mod_rewrite.so
登录后复制

b)将所有AllowOverride None改成AllowOverride All

public\.htaccess文件内容:

<IfModule mod_rewrite.c>
Options +FollowSymlinks -Multiviews
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [L,E=PATH_INFO:$1]
</IfModule>
登录后复制

4、创建测试数据
tprestful.sql

--
-- 数据库: `tprestful`
--

-- --------------------------------------------------------

--
-- 表的结构 `news`
--

CREATE TABLE IF NOT EXISTS `news` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `content` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT=&#39;新闻表&#39; AUTO_INCREMENT=1;

--
-- 转存表中的数据 `news`
--

INSERT INTO `news` (`id`, `title`, `content`) VALUES
(1, &#39;新闻1&#39;, &#39;新闻1内容&#39;),
(2, &#39;新闻2&#39;, &#39;新闻2内容&#39;),
(3, &#39;新闻3&#39;, &#39;新闻3内容&#39;),
(4, &#39;房价又涨了&#39;, &#39;据新华社消息:上海均价环比上涨5%&#39;);
登录后复制

5、修改数据库配置文件
application\database.php

<?php
return [
    // 数据库类型
    &#39;type&#39;           => &#39;mysql&#39;,
    // 服务器地址
    &#39;hostname&#39;       => &#39;127.0.0.1&#39;,
    // 数据库名
    &#39;database&#39;       => &#39;tprestful&#39;,
    // 用户名
    &#39;username&#39;       => &#39;root&#39;,
    // 密码
    &#39;password&#39;       => &#39;123456&#39;,
    // 端口
    &#39;hostport&#39;       => &#39;&#39;,
    // 连接dsn
    &#39;dsn&#39;            => &#39;&#39;,
    // 数据库连接参数
    &#39;params&#39;         => [],
    // 数据库编码默认采用utf8
    &#39;charset&#39;        => &#39;utf8&#39;,
    // 数据库表前缀
    &#39;prefix&#39;         => &#39;&#39;,
    // 数据库调试模式
    &#39;debug&#39;          => true,
    // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
    &#39;deploy&#39;         => 0,
    // 数据库读写是否分离 主从式有效
    &#39;rw_separate&#39;    => false,
    // 读写分离后 主服务器数量
    &#39;master_num&#39;     => 1,
    // 指定从服务器序号
    &#39;slave_no&#39;       => &#39;&#39;,
    // 是否严格检查字段是否存在
    &#39;fields_strict&#39;  => true,
    // 数据集返回类型 array 数组 collection Collection对象
    &#39;resultset_type&#39; => &#39;array&#39;,
    // 是否自动写入时间戳字段
    &#39;auto_timestamp&#39; => false,
    // 是否需要进行SQL性能分析
    &#39;sql_explain&#39;    => false,
];
登录后复制

6、定义restful风格的路由规则,
application\route.php

<?php
use think\Route;
Route::get(&#39;/&#39;,function(){
    return &#39;Hello,world!&#39;;
});
Route::get(&#39;news/:id&#39;,&#39;index/News/read&#39;);	//查询
Route::post(&#39;news&#39;,&#39;index/News/add&#39;); 		//新增
Route::put(&#39;news/:id&#39;,&#39;index/News/update&#39;); //修改
Route::delete(&#39;news/:id&#39;,&#39;index/News/delete&#39;); //删除
//Route::any(&#39;new/:id&#39;,&#39;News/read&#39;); 		// 所有请求都支持的路由规则
登录后复制

7、新建模型
application\index\model\News.php

<?php
namespace app\index\model;
use think\Model;
class News extends Model{
	protected $pk = &#39;id&#39;;
	//protected static $table = &#39;news&#39;;
}
登录后复制

8、新建控制器
application\index\controller\News.php

<?php
namespace app\index\controller;
use think\Request;
use think\controller\Rest;

class News extends Rest{
	public function rest(){
        switch ($this->method){
			case &#39;get&#39;: 	//查询
				$this->read($id);
				break;
			case &#39;post&#39;:	//新增
				$this->add();
				break;
			case &#39;put&#39;:		//修改
				$this->update($id);
				break;
			case &#39;delete&#39;:	//删除
				$this->delete($id);
				break;
			
        }
    }
    public function read($id){
		$model = model(&#39;News&#39;);
		//$data = $model::get($id)->getData();
		//$model = new NewsModel();
		$data=$model->where(&#39;id&#39;, $id)->find();// 查询单个数据
		return json($data);
    }
	
	public function add(){
		$model = model(&#39;News&#39;);
		$param=Request::instance()->param();//获取当前请求的所有变量(经过过滤)
		if($model->save($param)){
			return json(["status"=>1]);
		}else{
			return json(["status"=>0]);
		}
    }
	public function update($id){
		$model = model(&#39;News&#39;);
		$param=Request::instance()->param();
		if($model->where("id",$id)->update($param)){
			return json(["status"=>1]);
		}else{
			return json(["status"=>0]);
		}
    }
	public function delete($id){
		
		$model = model(&#39;News&#39;);
		$rs=$model::get($id)->delete();
		if($rs){
			return json(["status"=>1]);
		}else{
			return json(["status"=>0]);
		}
    }
}
登录后复制

9、测试
a)、访问入口文件,默认在public\index.php

b)、客户端测试restful的get、post、put、delete方法

client\client.php

<?php
require_once &#39;./ApiClient.php&#39;;

$param = array(
  &#39;title&#39; => &#39;房价又涨了&#39;,
  &#39;content&#39; => &#39;据新华社消息:上海均价环比上涨5%&#39;
);
$api_url = &#39;http://www.tp5-restful.com/news/4&#39;; 
$rest = new restClient($api_url, $param, &#39;get&#39;);
$info = $rest->doRequest();
//$status = $rest->status;//获取curl中的状态信息


$api_url = &#39;http://www.tp5-restful.com/news&#39;; 
$rest = new restClient($api_url, $param, &#39;post&#39;);
$info = $rest->doRequest();

$api_url = &#39;http://www.tp5-restful.com/news/4&#39;; 
$rest = new restClient($api_url, $param, &#39;put&#39;);
$info = $rest->doRequest();

echo &#39;<pre/>&#39;;
print_r($info);exit;

$api_url = &#39;http://www.tp5-restful.com/news/4&#39;; 
$rest = new restClient($api_url, $param, &#39;delete&#39;);
$info = $rest->doRequest();
?>
登录后复制

请求工具类
client\ApiClient.php

<?php
class restClient
{
  //请求的token
  const token=&#39;yangyulong&#39;;
  
  //请求url
  private $url;
    
  //请求的类型
  private $requestType;
    
  //请求的数据
  private $data;
    
  //curl实例
  private $curl;
  
  public $status;
  
  private $headers = array();
  /**
   * [__construct 构造方法, 初始化数据]
   * @param [type] $url     请求的服务器地址
   * @param [type] $requestType 发送请求的方法
   * @param [type] $data    发送的数据
   * @param integer $url_model  路由请求方式
   */
  public function __construct($url, $data = array(), $requestType = &#39;get&#39;) {
      
    //url是必须要传的,并且是符合PATHINFO模式的路径
    if (!$url) {
      return false;
    }
    $this->requestType = strtolower($requestType);
    $paramUrl = &#39;&#39;;
    // PATHINFO模式
    if (!empty($data)) {
      foreach ($data as $key => $value) {
        $paramUrl.= $key . &#39;=&#39; . $value.&#39;&&#39;;
      }
      $url = $url .&#39;?&#39;. $paramUrl;
    }
      
    //初始化类中的数据
    $this->url = $url;
      
    $this->data = $data;
    try{
      if(!$this->curl = curl_init()){
        throw new Exception(&#39;curl初始化错误:&#39;);
      };
    }catch (Exception $e){
      echo &#39;<pre class="brush:php;toolbar:false">&#39;;
      print_r($e->getMessage());
      echo &#39;
'; } curl_setopt($this->curl, CURLOPT_URL, $this->url); curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1); //curl_setopt($this->curl, CURLOPT_HEADER, 1); } /** * [_post 设置get请求的参数] * @return [type] [description] */ public function _get() { } /** * [_post 设置post请求的参数] * post 新增资源 * @return [type] [description] */ public function _post() { curl_setopt($this->curl, CURLOPT_POST, 1); curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data); } /** * [_put 设置put请求] * put 更新资源 * @return [type] [description] */ public function _put() { curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT'); } /** * [_delete 删除资源] * delete 删除资源 * @return [type] [description] */ public function _delete() { curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); } /** * [doRequest 执行发送请求] * @return [type] [description] */ public function doRequest() { //发送给服务端验证信息 if((null !== self::token) && self::token){ $this->headers = array( 'Client-Token:'.self::token,//此处不能用下划线 'Client-Code:'.$this->setAuthorization() ); } //发送头部信息 $this->setHeader(); //发送请求方式 switch ($this->requestType) { case 'post': $this->_post(); break; case 'put': $this->_put(); break; case 'delete': $this->_delete(); break; default: curl_setopt($this->curl, CURLOPT_HTTPGET, TRUE); break; } //执行curl请求 $info = curl_exec($this->curl); //获取curl执行状态信息 $this->status = $this->getInfo(); return $info; } /** * 设置发送的头部信息 */ private function setHeader(){ curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers); } /** * 生成授权码 * @return string 授权码 */ private function setAuthorization(){ $authorization = md5(substr(md5(self::token), 8, 24).self::token); return $authorization; } /** * 获取curl中的状态信息 */ public function getInfo(){ return curl_getinfo($this->curl); } /** * 关闭curl连接 */ public function __destruct(){ curl_close($this->curl); } }
登录后复制

完整代码从我github下载:https://github.com/phper-hard/tp5-restful

以上是thinkphp5.0极速搭建restful风格接口层(实例解析)的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

thinkphp项目怎么运行 thinkphp项目怎么运行 Apr 09, 2024 pm 05:33 PM

运行 ThinkPHP 项目需要:安装 Composer;使用 Composer 创建项目;进入项目目录,执行 php bin/console serve;访问 http://localhost:8000 查看欢迎页面。

thinkphp有几个版本 thinkphp有几个版本 Apr 09, 2024 pm 06:09 PM

ThinkPHP 拥有多个版本,针对不同 PHP 版本而设计。主要版本包括 3.2、5.0、5.1 和 6.0,而次要版本用于修复 bug 和提供新功能。当前最新稳定版本为 ThinkPHP 6.0.16。在选择版本时,需考虑 PHP 版本、功能需求和社区支持。建议使用最新稳定版本以获得最佳性能和支持。

thinkphp怎么运行 thinkphp怎么运行 Apr 09, 2024 pm 05:39 PM

ThinkPHP Framework 的本地运行步骤:下载并解压 ThinkPHP Framework 到本地目录。创建虚拟主机(可选),指向 ThinkPHP 根目录。配置数据库连接参数。启动 Web 服务器。初始化 ThinkPHP 应用程序。访问 ThinkPHP 应用程序 URL 运行。

laravel和thinkphp哪个好 laravel和thinkphp哪个好 Apr 09, 2024 pm 03:18 PM

Laravel 和 ThinkPHP 框架的性能比较:ThinkPHP 性能通常优于 Laravel,专注于优化和缓存。Laravel 性能良好,但对于复杂应用程序,ThinkPHP 可能更适合。

thinkphp怎么安装 thinkphp怎么安装 Apr 09, 2024 pm 05:42 PM

ThinkPHP 安装步骤:准备 PHP、Composer、MySQL 环境。使用 Composer 创建项目。安装 ThinkPHP 框架及依赖项。配置数据库连接。生成应用代码。启动应用并访问 http://localhost:8000。

开发建议:如何利用ThinkPHP框架实现异步任务 开发建议:如何利用ThinkPHP框架实现异步任务 Nov 22, 2023 pm 12:01 PM

《开发建议:如何利用ThinkPHP框架实现异步任务》随着互联网技术的迅猛发展,Web应用程序对于处理大量并发请求和复杂业务逻辑的需求也越来越高。为了提高系统的性能和用户体验,开发人员常常会考虑利用异步任务来执行一些耗时操作,比如发送邮件、处理文件上传、生成报表等。在PHP领域,ThinkPHP框架作为一款流行的开发框架,提供了一些便捷的方式来实现异步任务。

thinkphp性能怎么样 thinkphp性能怎么样 Apr 09, 2024 pm 05:24 PM

ThinkPHP 是一款高性能的 PHP 框架,具备缓存机制、代码优化、并行处理和数据库优化等优势。官方性能测试显示,它每秒可处理超过 10,000 个请求,实际应用中被广泛用于京东商城、携程网等大型网站和企业系统。

基于ThinkPHP6和Swoole的RPC服务实现文件传输功能 基于ThinkPHP6和Swoole的RPC服务实现文件传输功能 Oct 12, 2023 pm 12:06 PM

基于ThinkPHP6和Swoole的RPC服务实现文件传输功能引言:随着互联网的发展,文件传输在我们的日常工作中变得越来越重要。为了提高文件传输的效率和安全性,本文将介绍基于ThinkPHP6和Swoole的RPC服务实现文件传输功能的具体实现方法。我们将使用ThinkPHP6作为Web框架,利用Swoole的RPC功能来实现跨服务器的文件传输。一、环境准

See all articles