galafeno/lingo
Composer 安装命令:
composer require galafeno/lingo
包简介
A neat REST abstraction
README 文档
README
Lingo is a package for Laravel that provides a layer of abstraction to any REST service. so it is possible to encapsulate http communication concepts in a much closer object-oriented design and thus improve developer experience.
Installation
Use the package manager composer to install Lingo.
composer require galafeno/lingo
Usage
Use the command make:lingo to initialize a new Lingo inside your application.
php artisan make:lingo AwesomeApi --base_url=https://awesome.api/v1
That command creates a class called AwesomeApiLingo within the folder App\Lingos.
To model the API you should add the endpoints inside the sync section into the AwesomeApiLingo class.
protected $sync = [ 'base_url' => 'https://awesome.api/v1', 'commands' => [ 'getMovie' => [ 'verb' => 'get', 'url' => "/movies/{:?}" ], ] ];
After that, you can use your Lingo inside your application like so:
$movie = Lingo::awesomeApi()->command('getMovie',1)->send(); echo $movie->name; // Batman v Superman: Dawn of Justice
The command method should receive at least one parameter (the command name). In that case it received 2 parameters because the getMovie command has a binding value (marked with the {:?} wildcard).
Custom Headers
Lingo was designed to handle json data type, so it will always append the Content-Type: application/json and Accept: application/json into default headers. To define another headers, create a headers property into your Lingo Class
protected $headers = [ 'DomainId' => 15, 'SafeMode' => 'Unguarded' ];
That will produce the follow headers in every request:
{
"Content-Type": "application/json",
"Accept": "application/json",
"DomainId": "15",
"SafeMode": "Unguarded"
}
You can also define extra headers in runtime like so:
Lingo::awesomeApi() ->command('getMovie',1) ->withHeaders(['Scope' => 'readOnly']) ->send();
Query parameters
To define query parameters, create a params property into your Lingo Class
protected $params = [ 'start' => '2020-02-02', 'end' => '2020-04-04' ];
That will insert the follow query parameters in every request:
GET https://awesome.api/v1/movies/1?start=2020-02-02&end=2020-04-04
You can also define extra query parameters in runtime like so:
Lingo::awesomeApi() ->command('getMovie',1) ->withParams(['user_id' => 1]) ->send();
Body Parameters
To define body parameters, create a data property into your Lingo Class
protected $data = [ 'username' => 'superuser', 'email' => 'superuser@super.user' ];
That will insert the follow body parameters in every request:
POST https://awesome.api/v1/movies { "username": "superuser", "email": "superuser@super.user" }
You can also define extra body parameters in runtime like so:
Lingo::awesomeApi() ->command('getMovie',1) ->withData(['user_id' => 1]) ->send();
Closure Commands
Usually you should use Lingo as a way to map endpoints into commands. But using closure command syntax you can trigger a function instead of a real http request. That is a convenient way to append metadata about your api. To do so, use the keyword function inside your command configuration. Then just add the referred function in your Lingo class.
'commands' => [ ... 'list' => [ 'function' => 'getCommandList' ], ... ]; ... protected function getCommandList($bindings) { foreach ($this->sync['commands'] as $command) { if ( isset($command['verb']) && isset($command['url']) ){ echo strtoupper($command['verb']) . " " . $command['url'] . PHP_EOL; } } } ... Lingo::awesomeApi()->command('list')->send(); // GET /peoples // POST /peoples // GET peoples/{:?} // PUT peoples/{:?} // DELETE peoples/{:?}
Handling Authentication
In real world applications REST services implements some type of authentication scheme. If you are dealing with a simple approach like a signature or key into request headers you should simply use the withHeaders command to attach your auth configuration into Lingo. But some services utilizes specifics schemes. To handle it you should define an auth configuration within your lingo class. currently, this package supports apiKeys and oauth2 auth methods.
apiKeys
That method will attach the key configuration as a query parameter.
protected $sync = [ 'base_url' => 'https://protected.rest/v1', 'auth' => [ 'apiKeys' => [ 'my-key' => 'my-secret' ] ], 'commands' => [ ... ] ];
GET https://protected.rest/v1/someurl?my-key=my-secret
oauth2
That method will handle the oauth2 flow to retrieve the jwt and cache it using your application cache configuration.
protected $sync = [ 'base_url' => 'https://protected.rest', 'auth' => [ 'oauth2' => [ 'url' => '/oauth/token', 'grant_type' => 'client_credentials', 'client_id' => 'my-client-id', 'client_secret' => 'my-client-secret' ] ], 'commands' => [ ... ] ];
Mockup mode
While testing your application you must define APP_ENV=testing in your .env to activate Lingo mockup mode. While using this mode the package will bypass any real request by a mocked static data. You should define that data within your command configuration section using the shouldReturn key.
protected $sync = [ 'base_url' => 'https://service.rest/v1', 'commands' => [ 'getMovie' => [ 'verb' => 'get', 'url' => "/movies/{:?}", 'shouldReturn' => [ 'id' => 1 'name' => 'static name', 'genre' => 'drama', 'length' => 97 ] ], ] ]; ... $movie = Lingo::awesomeApi()->command('getMovie',1)->send(); echo $movie->name; // static name
You can also set mockup mode in runtime like so:
$movie = Lingo::awesomeApi()->command('getMovie',1)->withMockup(true)->send(); echo $movie->name; // static name
Lingo use static as default mockup data mode. But you may set function mode with the mockup keyword. with that, Lingo will rely on a function to generate the mockup data.
protected $sync = [ 'base_url' => 'https://service.rest/v1', 'commands' => [ 'getMovie' => [ 'verb' => 'get', 'url' => "/movies/{:?}", 'mockup' => 'function', 'shouldReturn' => 'makeMovie' ], ] ]; ... protected function makeMovie($bindings) { $faker = \Faker\Factory::create(); return (object)[ 'id' => $bindings[0], 'name' => $faker->name, 'length' => $faker->numberBetween(90,180) ]; } ... $movie = Lingo::awesomeApi()->command('getMovie',1)->send(); echo $movie->name; // name generated by faker
Async Communication
If your application utilize AWS infrastructure you may configure asynchronous message within your Lingo class. To do so, you must configure your async section.
protected $async = [ 'queue' => 'myqueue', 'commands' => [ 'sendEmail' => [ 'action' => 'SendEmail' ] ] ];
To send a asynchronous you have to use the async method.
Lingo::awesomeApi()->command('sendEmail') ->withData($data) ->async() ->send();
That will push to your sqs queue the payload:
[
'action' => 'sendEmail',
'data' => $data
]
Roadmap
- unit and feature tests
- export
syncsection to a swagger file - accepts a closure into
shouldReturnsection, so you can deal with dynamically generated mockup data - add a polymorphic option into
make:lingo. it will be nice create, for instance aPaymentLingothat is a interface and aStripeLingoas a concrete class that implementsPaymentLingo - to allow a sync command trigger a closure or a class method instead of a http request.
- custom exceptions
- a built-in log system
Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
License
galafeno/lingo 适用场景与选型建议
galafeno/lingo 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6 次下载、GitHub Stars 达 2, 最近一次更新时间为 2020 年 05 月 22 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「php」 「json」 「http」 「rest」 「aws」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 galafeno/lingo 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 galafeno/lingo 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 galafeno/lingo 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
repository php library
Kinikit - PHP Application development framework MVC component
ext-json wrapper with sane defaults
A package to cast json fields, each sub-keys is castable
swagger-php - Generate interactive documentation for your RESTful API using phpdoc annotations
Get wordpress nav menus and share the main site menus with the child sites.
统计信息
- 总下载量: 6
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 4
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2020-05-22