百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Thinkphp5.0极速搭建restful风格接口层

ccwgpt 2025-05-24 12:49 42 浏览 0 评论

下面是基于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='新闻表' AUTO_INCREMENT=1;
 
--
 
-- 转存表中的数据 `news`
 
--
 
INSERT INTO `news` (`id`, `title`, `content`) VALUES
 
(1, '新闻1', '新闻1内容'),
 
(2, '新闻2', '新闻2内容'),
 
(3, '新闻3', '新闻3内容'),
 
(4, '房价又涨了', '据新华社消息:上海均价环比上涨5%');

5、修改数据库配置文件

application\database.php

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

6、定义restful风格的路由规则,

application\route.php

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

7、新建模型

application\index\model\News.php

<?php
 
namespace app\index\model;
 
use think\Model;
 
class News extends Model{
 
    protected $pk = 'id';
 
    //protected static $table = 'news';
 
}

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 'get':     //查询
 
                $this->read($id);
 
                break;
 
            case 'post':    //新增
 
                $this->add();
 
                break;
 
            case 'put':     //修改
 
                $this->update($id);
 
                break;
 
            case 'delete':  //删除
 
                $this->delete($id);
 
                break;
 
        }
 
    }
 
    public function read($id){
 
        $model = model('News');
 
        //$data = $model::get($id)->getData();
 
        //$model = new NewsModel();
 
        $data=$model->where('id', $id)->find();// 查询单个数据
 
        return json($data);
 
    }
 
    public function add(){
 
        $model = model('News');
 
        $param=Request::instance()->param();//获取当前请求的所有变量(经过过滤)
 
        if($model->save($param)){
 
            return json(["status"=>1]);
 
        }else{
 
            return json(["status"=>0]);
 
        }
 
    }
 
    public function update($id){
 
        $model = model('News');
 
        $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('News');
 
        $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 './ApiClient.php';
 
$param = array(
 
  'title' => '房价又涨了',
 
  'content' => '据新华社消息:上海均价环比上涨5%'
 
);
 
$api_url = 'http://www.tp5-restful.com/news/4';
 
$rest = new restClient($api_url, $param, 'get');
 
$info = $rest->doRequest();
 
//$status = $rest->status;//获取curl中的状态信息
 
$api_url = 'http://www.tp5-restful.com/news';
 
$rest = new restClient($api_url, $param, 'post');
 
$info = $rest->doRequest();
 
$api_url = 'http://www.tp5-restful.com/news/4';
 
$rest = new restClient($api_url, $param, 'put');
 
$info = $rest->doRequest();
 
echo '<pre/>';
 
print_r($info);exit;
 
$api_url = 'http://www.tp5-restful.com/news/4';
 
$rest = new restClient($api_url, $param, 'delete');
 
$info = $rest->doRequest();
 
?>

请求工具类

client\ApiClient.php

<?php
 
class restClient
{
 
  //请求的token
 
  const token='yangyulong';
 
  //请求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 = 'get') {
 
    //url是必须要传的,并且是符合PATHINFO模式的路径
 
    if (!$url) {
 
      return false;
 
    }
 
    $this->requestType = strtolower($requestType);
 
    $paramUrl = '';
 
    // PATHINFO模式
 
    if (!empty($data)) {
 
      foreach ($data as $key => $value) {
 
        $paramUrl.= $key . '=' . $value.'&';
 
      }
 
      $url = $url .'?'. $paramUrl;
 
    }
 
    //初始化类中的数据
 
    $this->url = $url;
 
    $this->data = $data;
 
    try{
 
      if(!$this->curl = curl_init()){
 
        throw new Exception('curl初始化错误:');
 
      };
 
    }catch (Exception $e){
 
      echo '<pre>';
 
      print_r($e->getMessage());
 
      echo '</pre>';
 
    }
 
    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

相关推荐

用Steam启动Epic游戏会更快吗?(epic怎么用steam启动)

Epic商店很香,但也有不少抱怨,其中一条是启动游戏太慢。那么,如果让Steam启动Epic游戏,会不会速度更快?众所周知,Steam可以启动非Steam游戏,方法是在客户端左下方点击“添加游戏”,然...

Docker看这一篇入门就够了(dockerl)

安装DockerLinux:$curl-fsSLhttps://get.docker.com-oget-docker.sh$sudoshget-docker.sh注意:如果安装了旧版...

AYUI 炫丽PC开发UI框架2016年6月15日对外免费开发使用 [1]

2016年6月15日,我AY对外发布AYUI(WPF4.0开发)的UI框架,开发时候,你可以无任何影响的去开发PC电脑上的软件exe程序。AYUI兼容XP操作系统,在Win7/8/8.1/10上都顺利...

别再说C#/C++套壳方案多了!Tauri这“借壳生蛋”你可能没看懂!

浏览器套壳方案,C#和C++有更多,你说的没错,从数量和历史积淀来看,C#和C++确实有不少方式来套壳浏览器,让Web内容在桌面应用里跑起来。但咱们得把这套壳二字掰扯清楚,因为这里面学问可大了!不同的...

OneCode 核心概念解析——Page(页面)

在接触到OneCode最先接触到的就是,Page页面,在低代码引擎中,页面(Page)设计的灵活性是平衡“快速开发”与“复杂需求适配”的关键。以下从架构设计、组件系统、配置能力等维度,解析确...

React是最后的前端框架吗,为什么这么说的?

油管上有一位叫Theo的博主说,React是终极前端框架,为什么这么说呢?让我们来看看其逻辑:这个标题看起来像假的,对吧?React之后明明有无数新框架诞生,凭什么说它是最后一个?我说的“最后一个”不...

面试辅导(二):2025前端面试密码:用3个底层逻辑征服技术官

面试官放下简历,手指在桌上敲了三下:"你上次解决的技术难题,现在回头看有什么不足?"眼前的候选人瞬间僵住——这是上周真实发生在蚂蚁金服终面的场景。2025年的前端战场早已不是框架熟练...

前端新星崛起!Astro框架能否终结React的霸主地位?

引言:当"背着背包的全能选手"遇上"轻装上阵的短跑冠军"如果你是一名前端开发者,2024年的框架之争绝对让你眼花缭乱——一边是React这位"背着全家桶的全能选...

基于函数计算的 BFF 架构(基于函数计算的 bff 架构是什么)

什么是BFFBFF全称是BackendsForFrontends(服务于前端的后端),起源于2015年SamNewman一篇博客文章《Pattern:BackendsFor...

谷歌 Prompt Engineering 白皮书:2025年 AI 提示词工程的 10 个技巧

在AI技术飞速发展的当下,如何更高效地与大语言模型(LLM)沟通,以获取更准确、更有价值的输出,成为了一个备受关注的问题。谷歌最新发布的《PromptEngineering》白皮书,为这一问题提供了...

光的艺术:灯具创意设计(灯光艺术作品展示)

本文转自|艺术与设计微信号|artdesign_org_cn“光”是文明的起源,是思维的开端,同样也是人类睁眼的开始。每个人在出生一刻,便接受了光的照耀和洗礼。远古时候,人们将光奉为神明,用火来...

MoE模型已成新风口,AI基础设施竞速升级

机器之心报道编辑:Panda因为基准测试成绩与实际表现相差较大,近期开源的Llama4系列模型正陷入争议的漩涡之中,但有一点却毫无疑问:MoE(混合专家)定然是未来AI大模型的主流范式之一。...

Meta Spatial SDK重大改进:重塑Horizon OS应用开发格局

由文心大模型生成的文章摘要Meta持续深耕SpatialSDK技术生态,提供开自去年9月正式推出以来,Meta持续深耕其SpatialSDK技术生态,通过一系列重大迭代与功能增强,不断革新H...

&quot;上云&quot;到底是个啥?用&quot;租房&quot;给你讲明白IaaS/PaaS/SaaS的区别

半夜三点被机房报警电话惊醒,顶着黑眼圈排查服务器故障——这是十年前互联网公司运维的日常。而现在,程序员小王正敷着面膜刷剧,因为公司的系统全"搬"到了云上。"部署到云上"...

php宝塔搭建部署thinkphp机械设备响应式企业网站php源码

大家好啊,欢迎来到web测评。本期给大家带来一套php开发的机械设备响应式企业网站php源码,上次是谁要的系统项目啊,帮你找到了,还说不会搭建,让我帮忙录制一期教程,趁着今天有空,简单的录制测试了一下...

取消回复欢迎 发表评论: