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

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

yuyutoo 2024-11-16 02:39 4 浏览 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

相关推荐

从头再来,再见了我曾奋斗的地方

今天,我告别了奋斗二十年的地,就现在也不敢相信曾经是那么的辉煌那么让我骄傲的厂子今天确是也要告别了,我们不知道该怨谁该谁买单可苦的是我们还得从头再来...

《万古神帝》第4202章(评)咬定神树不放松,第二儒祖仍在破局中

各位老铁,酒窝突然有了一个匪夷所思的猜想,从突袭天庭,再到夺取世界树,到天姥和若尘打上天界对战第二儒祖和慕容主宰。这一切会不会只是时空人祖一开始就谋划好的,引蛇出洞之计?第二儒祖乃至整个神界也只不过是...

香皂和透明皂可以混用吗?

香皂和透明皂是家庭常用物品,使用频率比较高。但是,有些市民认为香皂比较柔和,香味也比较好,因此喜欢用香皂给孩子洗衣服。而有些成年人,特别是男性,觉得透明皂的去污能力强,有时候会使用透明皂洗手或洗澡。那...

批评别人的技巧

批评和赞美是一对反义词,但在说话这门艺术里,两者不过是两种与人交流沟通的不同方式而已,赞美侧重于一个人的优点和长处,批评侧重于一个人的缺点和不足。赞美人需要讲究方式和技巧,批评人同样不能草率从事。批评...

山东2020春季高考技能考试主考学校及考试安排来了

山东2020年春季高考技能考试安排在7月14日—20日进行,各类别具体考试时间由主考学校自主确定。考生请于7月11日起登录山东省教育招生考试院招生考试信息平台(http://wsbm.sdzk.cn)...

石河子大学2019-2020学年第二学期选课通知

它来了,它来了小石带着秘籍来了!又快到了每学期的选课时间内心是不是既兴奋又紧张敲黑板,划重点!为保证选课工作的顺利进行现将选课事宜安排如下你想要的课程安排选课时间及其相关要求...

“奋进新时代”主题成就展线上开展!一起为山西单元云端打call

登录网址,点击按钮,“祝融号”火星车模型、天问一号着陆器模型、东风-17高超音速导弹等实物展品立刻呈现;跟随着语音讲解,奋进山西单元的精彩内容就跃然眼前……近日,“奋进新时代”主题成就展网上展馆上线。...

延边大学关于2021年秋季学期本(专)科教学运行工作安排的通知

关于2021年秋季学期本(专)科教学运行工作安排的通知根据学校《关于2021年秋季学期师生返校安排的通知》和《关于2021级新生报到相关事宜的通知》,为做好2021年秋季学期开学期间的本(专)科教学相...

阿里巴巴Yun OS智能手表Pay Watch亮相:深度整合支付宝

IT之家讯9月22日消息,刚刚我们报道了阿里巴巴智能手表亮相YunOS官网,本来以为阿里巴巴会重点介绍一下这款产品。没想到这款智能手表已经悄悄的登录淘宝众筹了。与此同时,它的名字也正式揭晓:Pay...

内网本机IP怎么查?外网本机IP地址查询方法

在工作中,我们或许要查看本机的ip地址,不是很懂电脑的人,对此可能会无从下手,今天飞飞就给你们分享外网/内网本机IP地址查询方法,感兴趣的往下看,非常简单,肯定可以学会...

查完成绩,你是不是还需要了解一下这个「奸笑脸」

各位假期生活过得如何?不管你是在各个城市享受旅行,或是已经摊在家里过着肥宅的快乐生活。都醒一醒吧!这一次不同于各种校园推送里的假消息是真的可以查成绩了!成绩已于今日上午...

小本本里装着大民生——“奋进新时代”主题成就展上的广西人大故事

...

“奋进新时代”主题成就展网上展馆发布上线

...

「鼠标」垂直鼠标再体验:多彩DELUX 90度垂直鼠 M618与M618PLUS

我因为用原来的鼠标时间比较久了,想换个姿势用鼠标。我仔细搜了一下,垂直鼠标,只找到罗技的MXVERTICAL和多彩的M618系列产品。因为我的初体验是罗技的MXVERTICAL,所以这篇叫“垂直...

说一个目前最让你焦虑的事?

来说说那些让你感到非常焦虑但是不被生活中你的亲人朋友所知道的吧,在这里说一下,写下来,聊一聊,互相温暖鼓励一下吧!...

取消回复欢迎 发表评论: