欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP編寫RESTful接口的方法

 更新時間:2016年02月21日 15:36:57   投稿:lijiao  
這篇文章主要為大家詳細介紹了PHP編寫RESTful接口的方法,如何使用PHP編寫RESTful接口,感興趣的小伙伴們可以參考一下

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

先舉個栗子
1、寫個HelloWorld.php,放到框架指定的目錄下(默認是和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"      
    }
  },
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。

相關(guān)文章

最新評論