溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

PHP怎么編寫RESTful接口

發(fā)布時間:2021-08-09 18:12:24 來源:億速云 閱讀:112 作者:chen 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“PHP怎么編寫RESTful接口”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

這是一個輕量級框架,專為快速開發(fā)RESTful接口而設(shè)計。如果你和我一樣,厭倦了使用傳統(tǒng)的MVC框架編寫微服務(wù)或者前后端分離的API接口,受不了為了一個簡單接口而做的很多多余的coding(和CTRL-C/CTRL-V),那么,你肯定會喜歡這個框架!

先舉個栗子
1、寫個HelloWorld.php,放到框架指定的目錄下(默認(rèn)是和index.php同級的apis/目錄)

/**
 * @path("/hw")
 */
class HelloWorld
{
  /** 
   * @route({"GET","/"})
   */
  public function doSomething() {
    return "Hello World!";
  }
}

2、瀏覽器輸入http://your-domain/hw/
你將看到:Hello World!就是這么簡單,不需要額外配置,不需要繼承也不需要組合。
發(fā)生了什么
回過頭看HelloWorld.php,特殊的地方在于注釋(@path,@route),沒錯,框架通過注釋獲取路由信息和綁定輸入輸出。但不要擔(dān)心性能,注釋只會在類文件修改后解析一次。更多的@注釋后面會說明。

再看個更具體的例子
這是一個登錄接口的例子

/**
 * 用戶權(quán)限驗證
 * @path("/tokens/") 
 */
class Tokens
{ 
  /**
   * 登錄
   * 通過用戶名密碼授權(quán)
   * @route({"POST","/accounts/"}) 
   * @param({"account", "$._POST.account"}) 賬號
   * @param({"password", "$._POST.password"}) 密碼
   * 
   * @throws ({"InvalidPassword", "res", "403 Forbidden", {"error":"InvalidPassword"} }) 用戶名或密碼無效
   * 
   * @return({"body"})  
   * 返回token,同cookie中的token相同,
   * {"token":"xxx", "uid" = "xxx"}
   *
   * @return({"cookie","token","$token","+365 days","/"}) 通過cookie返回token
   * @return({"cookie","uid","$uid","+365 days","/"}) 通過cookie返回uid
   */
  public function createTokenByAccounts($account, $password, &$token,&$uid){
    //驗證用戶
    $uid = $this->users->verifyPassword($account, $password);
    Verify::isTrue($uid, new InvalidPassword($account));
    $token = ...;
    return ['token'=>$token, 'uid'=>$uid];
  } 
  /**
   * @property({"default":"@Users"})  依賴的屬性,由框架注入
   * @var Users
   */
  public $users;
}

還能做什么

  • 依賴管理(依賴注入),

  • 自動輸出接口文檔(不是doxgen式的類、方法文檔,而是描述http接口的文檔)

  • 接口緩存

  • hook

配合ezsql訪問數(shù)據(jù)庫
ezsql是一款簡單的面向?qū)ο蟮膕ql構(gòu)建工具,提供簡單的基本sql操作。
接口

/** @path(/myclass) */
class MyClass{

  /**
  * @route({"GET","/do"})
  * @param({"arg0","$._GET.arg0"})
  */
  public doSomething($arg0){
    return Sql::select('xxx')->from('table_xxx')->where( 'xxx = ?', $arg0)->get($this->db);
  }
  /**
   * 依賴注入PDO實例
   * @property
   * @var PDO
   */
  public $db;
}

配置文件

{
  {
    "MyClass":{
      "properties":{
        "db":"@db1"   
      }
    },
  },
  "db1":{
    "singleton":true,
    "class":"PDO",
    "pass_by_construct":true,
    "properties":{
      "dsn":"mysql:host=127.0.0.1;dbname=xxx",
      "username":"xxxx",
      "passwd":"xxxx"      
    }
  },
}

“PHP怎么編寫RESTful接口”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI