starinc/abigail 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

starinc/abigail

Composer 安装命令:

composer require starinc/abigail

包简介

Abigail is the fork from marcj/php-rest-service, which is a simple and fast PHP class for server side RESTful APIs.

README 文档

README

Integration

Abigail is the fork from marcj/php-rest-service, which is a simple and fast PHP microservice framework for server side RESTful APIs.

Features

  • Easy to use syntax
  • Regular Expression support
  • Error handling through PHP Exceptions
  • Parameter validation through PHP function signature
  • Can return a summary of all routes or one route through OPTIONS method based on PHPDoc (if OPTIONS is not overridden)
  • Support of GET, POST, PUT, DELETE, PATCH, HEAD and OPTIONS
  • Suppress the HTTP status code with ?_suppress_status_code=1 (for clients that have troubles with that)
  • Supports ?_method=httpMethod as addition to the actual HTTP method.
  • With auto-generation through PHP's reflection

Installation

Create a composer.json:

{
  "require": {
    "starinc/abigail": "*"
  }
}

then run

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

After the installation, you need to include the vendor/autoload.php to make the class in your script available.

include 'vendor/autoload.php';

Requirements

  • PHP 7.4 and above.
  • PHPUnit to execute the test suite.
  • Setup PATH_INFO in mod_rewrite (.htaccess) or other webserver configuration

Example config

Apache webserver

#.htaccess
RewriteEngine On

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

Nginx webserver

// edit virtualhost /etc/nginx/conf.d/name_virtualhost_file
server {
 .. something params ...
 location / {
  include fastcgi_params;
     
  fastcgi_pass unix:/var/run/php-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;

Usage Demo

Way 1. The dirty & fast

use Abigail\Server;

Server::create('/')
    ->addGetRoute('test', function(){
        return 'Yay!';
    })
    ->addGetRoute('foo/(.*)', function($bar){
        return $bar;
    })
    ->addPostRoute('foo', function($field1, $field2) {
      // do stuff with $field1, $field2, etc.
      // or you can directly get them with $_POST['field1'].
    })
->run();

Way 2. Auto-Collection

index.php:

use Abigail\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);
    }

}

Generates following entry points:

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

Way 3. Custom rules with controller

index.php:

use Abigail\Server;

Server::create('/admin', new MyRestApi\Admin) //base entry points `/admin`
    ->setDebugMode(true) //prints the debug trace, line number and file if an 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;
    }
}

Responses

The response body is always an array (JSON per default) containing a status code and the actual data. If an exception has been thrown, it contains the status 500, the exception class name as error, and the message as message.

Some examples:

+ 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
  }

License

Licensed under the MIT License. See the LICENSE file for more details.

Take a look into the code, to get more information about the possibilities. It's well documented.

starinc/abigail 适用场景与选型建议

starinc/abigail 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 48 次下载、GitHub Stars 达 1, 最近一次更新时间为 2021 年 07 月 17 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「rest」 「api」 「restful」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 starinc/abigail 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 starinc/abigail 我们能提供哪些服务?
定制开发 / 二次开发

基于 starinc/abigail 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 48
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 4
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-07-17