vlad-dmitr/rest-service

PHPRestService 是一个简单且快速的 PHP 类,用于构建服务器端 RESTful API。

0.1.8 2020-12-25 17:30 UTC

This package is not auto-updated.

Last update: 2024-09-29 11:58:58 UTC


README

Php-Rest-Service 是一个简单且快速的 PHP 类,用于 RESTful JSON API。

Build Status

特性

  • 易用语法
  • 正则表达式支持
  • 通过 PHP 异常处理错误
  • 通过 PHP 函数签名进行参数验证
  • 可以通过 OPTIONS 方法返回所有路由的摘要或单个路由(如果 OPTIONS 没有被覆盖的话)
  • 支持 GETPOSTPUTDELETEPATCHHEADOPTIONS
  • 使用 ?_suppress_status_code=1 隐藏 HTTP 状态码(对于有问题的客户端)
  • 支持 ?_method=httpMethod 作为实际 HTTP 方法的补充。
  • 通过 PHP 的 reflection 自动生成

安装

创建一个 composer.json

{
    "require": {
        "marcj/php-rest-service": "*"
    }
}

然后运行

$ wget https://getcomposer.org.cn/composer.phar
$ php composer.phar install

安装后,您需要在您的脚本中包含 vendor/autoload.php 以使类可用。

include 'vendor/autoload.php';

要求

  • PHP 5.3 及以上。
  • PHPUnit 以执行测试套件。
  • 在 mod_rewrite (.htaccess) 或其他 webserver 配置中设置 PATH_INFO

示例配置:Apache web服务器

//.htaccess
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.+) index.php/$1 [L,QSA]

Nginx web服务器

// edit virtualhost /etc/nginx/conf.d/name_virtualhost_file
server {
 .. something params ...
 location / {
  include fastcgi_params;
     
  fastcgi_pass unix:/var/run/php5-fpm.sock;
  fastcgi_param SCRIPT_FILENAME $document_root/index.php;
 }
}

// and add line to /etc/nginx/fastcgi_params
fastcgi_param PATH_INFO $fastcgi_script_name;

使用演示

方式 1. 脏且快

use RestService\Server;

Server::create('/')
    ->addGetRoute('test', function(){
        return 'Yay!';
    })
    ->addGetRoute('foo/(.*)', function($bar){
        return $bar;
    })
->run();

方式 2. 自动收集

index.php:

use RestService\Server;

Server::create('/admin', 'myRestApi\Admin')
    ->collectRoutes()
->run();

MyRestApi/Admin.php:

namespace MyRestApi;

class Admin {

    /**
    * Checks if a user is logged in.
    *
    * @return boolean
    */
    public function getLoggedIn(){
        return $this->getContainer('auth')->isLoggedIn();
    }

    /**
    * @param string $username
    * @param string $password
    * return boolean
    */
    public function postLogin($username, $password){
        return $this->getContainer('auth')->doLogin($username, $password);
    }

    /**
     * @param string $server
     * @url stats/([0-9]+)
     * @url stats
     * @return string
     */
    public function getStats($server = '1'){
        return $this->getServerStats($server);
    }

}

生成以下入口点

    + GET  /admin/logged-in
    + POST /admin/login?username=&password=
    + GET  /admin/stats/([0-9]+)
    + GET  /admin/stats

方式 3. 使用控制器自定义规则

index.php:

use RestService\Server;

Server::create('/admin', new MyRestApi\Admin) //base entry points `/admin`
    ->setDebugMode(true) //prints the debug trace, line number and file if a exception has been thrown.

    ->addGetRoute('login', 'doLogin') // => /admin/login
    ->addGetRoute('logout', 'doLogout') // => /admin/logout

    ->addGetRoute('page', 'getPages')
    ->addPutRoute('page', 'addPage')
    ->addGetRoute('page/([0-9]+)', 'getPage')
    ->addDeleteRoute('page/([0-9]+)', 'deletePage')
    ->addPostRoute('page/([0-9]+)', 'updatePage')

    ->addGetRoute('foo/bar/too', 'doFooBar')

    ->addSubController('tools', \RestApi\Tools) //adds a new sub entry point 'tools' => admin/tools
        ->addDeleteRoute('cache', 'clearCache')
        ->addGetRoute('rebuild-index', 'rebuildIndex')
    ->done()

->run();

MyRestApi/Admin.php:

namespace MyRestApi;

class Admin {
    public function login($username, $password){

        if (!$this->validLogin($username, $password)
            throw new InvalidLoginException('Login is invalid or no access.');

        return $this->getToken();

    }

    public function logout(){

        if (!$this->hasSession()){
            throw new NoCurrentSessionException('There is no current session.');
        }

        return $this->killSession();

    }

    public function getPage($id){
        //...
    }
}

namespace RestAPI;

class Tools {
    /**
    * Clears the cache of the app.
    *
    * @param boolean $withIndex If true, it clears the search index too.
    * @return boolean True if the cache has been cleared.
    */
    public function clearCache($withIndex = false){
        return true;
    }
}

响应

响应体始终是一个包含状态码和实际数据的数组(默认为 JSON)。如果抛出了异常,则包含状态 500、错误类名称作为错误以及消息作为消息。

一些示例

+ GET admin/login?username=foo&password=bar
  =>
  {
     "status": "200",
     "data": true
  }

+ GET admin/login?username=foo&password=invalidPassword
  =>
  {
     "status": "500",
     "error": "InvalidLoginException",
     "message": "Login is invalid or no access"
  }

+ GET admin/login
  =>
  {
     "status: "400",
     "error": "MissingRequiredArgumentException",
     "message": "Argument 'username' is missing"
  }

+ GET admin/login?username=foo&password=invalidPassword
  With active debugMode we'll get:
  =>
  {
     "status": "500",
     "error": "InvalidLoginException",
     "message": "Login is invalid or no access",
     "line": 10,
     "file": "libs/RestAPI/Admin.class.php",
     "trace": <debugTrace>
  }

+ GET admin/tools/cache
  =>
  {
     "status": 200,
     "data": true
  }

许可证

根据 MIT 许可证授权。有关详细信息,请参阅 LICENSE 文件。

查看代码,以获取更多关于可能性的信息。它有良好的文档。

Bitdeli Badge