mdelariva / api-model
Requires
- php: >=7.0
- ext-json: *
- illuminate/cache: >=6
- illuminate/contracts: >=6
- illuminate/database: >=6
- illuminate/filesystem: >=6
- illuminate/http: >=6
- illuminate/pagination: >=6
- illuminate/support: >=6
- laravel/framework: >=6
README
基本Laravel API客户端,Eloquent风格。
安装
Composer
需要包
composer require mdelariva/api-model
并发布配置 Provider: MdelaRiva\ApiModel\Providers\ServiceProvider
php artisan vendor:publish
GIT
克隆仓库
git clone git@bitbucket.org:marianodelariva/api-model.git
并发布配置 Provider: MdelaRiva\ApiModel\Providers\ServiceProvider
php artisan vendor:publish
用法
1- 在.env
和/或config/apimodel.php
中填写配置
2- 从MdelaRiva\ApiModel\ApiModelAbstract
扩展你的模型
<?php
namespace App\Models;
use MdelaRiva\ApiModel\ApiModelAbstract;
class Article extends ApiModelAbstract
{
}
3- 在你的控制器中使用你的模型,就像使用Eloquent一样
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Article;
class ArticleController extends Controller
{
public function index()
{
// Find item
$article = Article::find( 1 );
$article = Article::findOrFail( 1 );
// Update item
$article->status = 2;
$article->save();
// Create item
$article = new Article();
$article->status = 2;
$article->save();
// Delete item
$article->delete();
Article::destroy( 1 );
// Full List
$articleList = Article::all();
// Query List
$articleList = Article::where( 'status', 2 )->orderBy( 'status' )->get();
// Single item
$article = Article::where( 'status', 2 )->orderBy( 'status', 'desc' )->first();
// Query object
$articleQuery = Article::query();
$articleList = $articleQuery::where( 'status', 2 )->get();
}
}
配置
config/apimodel.php
中的可用选项
选项 | .env | 必需 | 类型 | 描述 |
---|---|---|---|---|
default | APIMODEL_CONNECTION | Y | string | 默认连接选项的键,用于默认连接。如果你在模型中使用受保护的connection 属性,你将仅覆盖该模型的连接。 |
connections | - | Y | array | 可用的连接列表(单个或分组)(见下面的选项列表)。 |
单个连接选项
选项 | .env | 必需 | 类型 | 描述 |
---|---|---|---|---|
driver | - | Y | string | 远程API和查询方法之间的转换器。默认:\MdelaRiva\ApiModel\Drivers\Basic::class 。 |
connector | - | Y | string | API客户端连接器。默认:\MdelaRiva\ApiModel\Connectors\Connector::class 。 |
persist_type | - | Y | string | 身份验证保存持久类型。可用选项:cache 、session 。默认:cache 。 |
url | APIMODEL_HOST | Y | string | 远程API基本URL。例如:https://api.example.com/ 。 |
version | APIMODEL_VERSION | N | string | 远程API版本。如果填写,它将被附加到URL上。例如:v1.2 、3.2 、api 。 |
authorization | - | Y | array | 授权。见上述描述和选项。 |
verify | APIMODEL_VERIFY | N | bool|string | 请求的SSL证书验证行为。设置为TRUE 以启用SSL证书验证并使用操作系统提供的默认CA捆绑包。设置为FALSE 以禁用证书验证(这是不安全的!)设置为string 以提供CA捆绑包的路径,以使用自定义证书启用验证。 |
allow_redirects | - | N | bool | 描述请求的重定向行为。设置为TRUE 以启用最多5次重定向的正常重定向。默认:FALSE |
debug | - | N | bool | 设置为TRUE 以启用调试输出。默认:FALSE 。 |
wrappers | - | N | array | 包装器。集合响应的属性列表。 |
wrappers.collection.root | - | N | string | 包装器。包装集合的属性的名称。默认:data 。 |
wrappers.collection.pagination.total | - | N | string | 包装器。包装在分页信息对象中的总结果数量的属性的名称。默认:meta.total 。 |
cache | - | N | array | 缓存。缓存属性列表。 |
cache.enabled | - | N | bool | 缓存。启用/禁用缓存的全球标志。默认:null 。 |
cache.path | - | Y | string | 缓存。缓存存储路径。默认:storage_path( 'framework/cache/data/apimodel/' ) |
cache.ttl | - | N | int | 缓存。对象在缓存中存储的时间,单位为秒。默认:86400 。 |
throttler | - | N | array | 节流器。节流器属性列表。 |
throttler.throw_exception | - | N | bool | 节流器。如果请求过多,则返回FALSE 或抛出ThrottleRequestsException 异常。默认:FALSE 。 |
throttler.limits | - | N | array | 节流器。速率限制元素的列表。 |
超时 | - | N | int | 连接超时(秒)。 |
日志记录 | - | N | array | 日志记录。日志属性列表。 |
logging.enabled | - | N | bool | 日志记录。启用/禁用连接日志的标志。默认:false 。 |
logging.type | - | N | string | 日志记录。日志类型。可选值:requests 、cache 。如果为空,则记录所有类型。 |
认证
选项 | .env | 必需 | 类型 | 认证类型相关 | 描述 |
---|---|---|---|---|---|
type | - | Y | string | - | 认证类型。参见上面的可选值。 |
oauth_endpoint | - | - | string | oauth_2 | OAuth 端点。默认:oauth/token 。 |
oauth_base64header | - | - | bool | oauth_2 | 设置为 TRUE 以在认证头中发送 Token 而不是请求体。默认:FALSE 。 |
401_refresh_token | - | - | bool | oauth_2 | 设置为 TRUE 以在服务器返回 401 错误时自动刷新访问令牌。默认:FALSE 。 |
credentials | - | - | array | - | 凭证列表。 |
credentials.client_id | APIMODEL_CLIENT_ID | Y | string | oauth_2 | 客户端 ID。 |
credentials.client_secret | APIMODEL_CLIENT_SECRET | Y | string | oauth_2 | 客户端密钥。 |
credentials.query | - | Y | array | api_key_query | 通过查询发送的凭证 key => value 数组。 |
credentials.headers | - | Y | array | api_key_header | 通过头部发送的凭证 key => value 数组。 |
credentials.token | - | Y | string | bearer_token | Bearer 令牌。 |
credentials.username | - | Y | string | basic_auth | 登录时使用的用户名。 |
credentials.password | - | Y | string | basic_auth | 登录时使用的密码。 |
认证类型
选项 | 描述 |
---|---|
no_auth | 无认证。不发送任何参数。不需要 credentials 选项。 |
api_key_query | API 密钥。通过查询发送参数。 |
api_key_header | API 密钥。通过头部发送参数。 |
bearer_token | Bearer 令牌。令牌作为 Bearer 发送在认证头部。 |
basic_auth | 基本认证。用户名和密码作为 Base64 编码字符串发送在 Authorization 头部。 |
oauth_2 | OAuth 2.0。凭证发送到配置 oauth_endpoint 端点以获取令牌,并在认证头部中作为 Bearer 使用。在 credentials 选项中定义的所有属性(除 client_id 和 client_secret )都将发送到请求体中,以允许授权自定义(例如 grant_type 、scope )。 |
有关认证类型的更多信息,请参阅Postman 文档。
节流限制元素
选项 | 必需 | 类型 | 描述 |
---|---|---|---|
max_attempts | Y | int | 允许尝试的数量。 |
decay_seconds | Y | int | 允许尝试的时间(秒)。 |
日志记录
日志文件保存在存储目录中的 logs
文件夹内,文件名模式如下:apimodel-{connection_name}.log
。
记录的每个请求都具有使用的方法、URL、查询参数和日志类型。
有两种类型的日志
requests
:记录直接发出的 API 请求。cache
:记录缓存的 API 请求。
分组连接选项
您可以定义一个分组连接,该连接将遍历单个连接列表。如果模型设置了分组连接,则每次实例化时将使用单个连接。
选项 | 必需 | 类型 | 描述 |
---|---|---|---|
connections | Y | array | 单个连接名称列表。 |
配置示例
<?php
return [
'default' => env('APIMODEL_CONNECTION', 'default'),
'connections' => [
'connection_1' => [
'url' => 'https://api.example.com/',
],
'connection_2' => [
'url' => 'https://api.example.com/',
],
'connection_3' => [
'url' => 'https://api.example.com/',
],
'grouped_connection' => [
'connections' => [
'connection_1',
'connection_2',
'connection_3'
]
],
],
];
查询构建器驱动程序
此类包括用作查询构建器的方法,并定义将发送到 API 的请求参数。只要您构建一个扩展自 MdelaRiva\ApiModel\Drivers\QueryInterface
的驱动程序,就可以自由编写自己的驱动程序。
基本(默认)
API:https://bitbucket.org/marianodelariva/api-controller
命名空间:MdelaRiva\ApiModel\Drivers\Basic
- 允许的方法
查询方法 | API 参数发送 |
---|---|
where | {fieldName} |
whereIn | {fieldName} |
limit | limit |
orderBy | orderBy orderByDir |
按组分类 | 按组分类 |
- where
此方法允许您使用多个运算符,这些运算符将被转换为附加到参数名称的代码,并且远程API应理解。
运算符 | 附加的代码 | 注意 |
---|---|---|
> | _gt | |
>= | _ge | |
< | _lt | |
<= | _le | |
like | _ct | 值必须匹配 %(.*)% |
like | _pr | 值必须匹配 %(.*) |
like | _ap | 值必须匹配 (.*)% |
示例
Article::where( 'status', '>=', 2 )
->where( 'name', 'like', 'example%' )
->whereIn( 'section', [3,4] )
->orderBy( 'status', 'asc' )
->get();
API调用参数: status_ge=2&name_ap=example§ion[]=3§ion[]=4&orderBy=status&orderByDir=asc
.
Twitter - 推文搜索
API: https://developer.twitter.com/en/docs/tweets/search
命名空间: MdelaRiva\ApiModel\Drivers\Twitter\TweetsSearch
- 允许的方法
查询方法 | API 参数发送 |
---|---|
where | 查询={字段}:{值} |
limit | 最大结果数 |
最大结果数 | 最大结果数 |
按组分类 | 桶 |
桶 | 桶 |
标签 | 标签 |
开始日期 | 开始日期 |
结束日期 | 结束日期 |
下一个 | 下一个 |
标签 | 标签 |
- where
此方法构建查询
参数。
$operator
参数不予考虑,而$field
参数是Twitter运算符(完整列表)。与基本驱动程序不同,$value
必须是字符串。
示例
TweetsSearch::where( 'lang', 'pt' )
->where( 'query', 'Twitter Dev' )
->fromDate( new \DateTime( '2016-04-22' ) )
->groupBy( 'day' )
->limit( 10 )
->get();
API调用参数: query=Twitter Dev lang:pt&fromDate=201604220000&bucket=day&maxResults=10
.
预构建驱动程序
Twitter - 推文搜索
- API文档
- 命名空间:
MdelaRiva\ApiModel\Drivers\Twitter\TweetsSearch
YouTube数据API - 频道
- API文档
- 命名空间:
MdelaRiva\ApiModel\Drivers\Youtube\Channel
YouTube数据API - 搜索
- API文档
- 命名空间:
MdelaRiva\ApiModel\Drivers\Youtube\Search
缓存
config/apimodel.php
中的enabled
键是一个全局标志,用于启用/禁用缓存。如果为TRUE
,则存储所有GET请求的响应。如果为FALSE
,则不会存储任何响应。如果为null
,则取决于每个请求或模型配置。
使用的驱动程序: file
用法
- 查询
用于存储特定的查询(全局标志必须为TRUE
或null
),并刷新它
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Article;
class ArticleController extends Controller
{
public function index()
{
// Cache using default configuration
$articleQuery = Article::cacheQuery();
$articleList = $articleQuery::where( 'status', 2 )->orderBy( 'status' )->get();
// Query inline
$articleQuery = Article::cacheQuery()->where( 'status', 2 )->orderBy( 'status' )->get();
// Cache using specific TTL (30 seconds)
$articleQuery = Article::cacheQuery( FALSE, 30 );
$articleList = $articleQuery::where( 'status', 2 )->orderBy( 'status' )->get();
// Make request, refreshing cache
$articleQuery = Article::cacheQuery( TRUE );
$articleList = $articleQuery::where( 'status', 2 )->orderBy( 'status' )->get();
}
}
- 清空
按模型清空
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Article;
class ArticleController extends Controller
{
public function index()
{
// Flush all Article cache
Article::cacheFlush();
}
}
模型
可用方法
这是一个调用连接的方法列表
all
call
get
find
findOrFail
first
firstOrNew
pagination
delete
destroy
save
配置
- 分页
定义分页时返回的项目数量。
<?php
namespace App\Models;
use MdelaRiva\ApiModel\ApiModelAbstract;
class Article extends ApiModelAbstract
{
protected $perPage = 20;
}
- 连接
受保护的$connection
属性(字符串)必须匹配上述apimodel配置文件中connection
数组中的一个键。
<?php
namespace App\Models;
use MdelaRiva\ApiModel\ApiModelAbstract;
class Article extends ApiModelAbstract
{
protected $connection = 'twitter';
}
- 端点
如果您的模型名称无法匹配API端点,您可以手动定义它
<?php
namespace App\Models;
use MdelaRiva\ApiModel\ApiModelAbstract;
class SomeEndpoint extends ApiModelAbstract
{
protected $endpoint = 'endpoint';
}
- 驱动程序
手动设置驱动程序(这将覆盖apimodel文件配置)
<?php
namespace App\Models;
use MdelaRiva\ApiModel\ApiModelAbstract;
class SomeEndpoint extends ApiModelAbstract
{
protected $driver = \MdelaRiva\ApiModel\Drivers\Youtube\Channel::class;
}
- 自定义调用
您可以为自己创建自定义调用的方法
<?php
namespace App\Models;
use MdelaRiva\ApiModel\ApiModelAbstract;
class Article extends ApiModelAbstract
{
public static function test( $params )
{
return self::call( [ 'test' ], 'POST', $params );
}
}
- 缓存
用于存储由模型执行的所有GET请求(全局缓存标志必须为TRUE
或null
),以及/或TTL(以秒为单位)
<?php
namespace App\Models;
use MdelaRiva\ApiModel\ApiModelAbstract;
class Article extends ApiModelAbstract
{
public $cache = TRUE;
protected $cacheTtl = 30;
}
预构建模型
Twitter - 用户
- API文档
- 命名空间:
MdelaRiva\ApiModel\Models\Twitter\User
YouTube数据API - 频道
- API文档
- 命名空间:
MdelaRiva\ApiModel\Models\Youtube\Channel
YouTube数据API - 搜索
- API文档
- 命名空间:
MdelaRiva\ApiModel\Models\Youtube\Search
示例
Twitter集成
- 配置
<?php
return [
'default' => env('APIMODEL_CONNECTION', 'default'),
'connections' => [
'twitter' => [
'url' => 'https://api.twitter.com/',
'version' => '1.1',
'credentials' => [
'useAuthorizationHeader' => TRUE,
'grant_type' => 'client_credentials',
'client_id' => env( 'APIMODEL_CLIENT_ID' ),
'client_secret' => env( 'APIMODEL_CLIENT_SECRET' ),
],
'wrappers' => [
'collection' => [
'root' => 'results',
],
],
],
],
];
- 模型
使用手动调用
<?php
namespace App\Models;
use MdelaRiva\ApiModel\ApiModelAbstract;
class Twitter extends ApiModelAbstract
{
protected $connection = 'twitter';
public function __construct( array $attributes = array() )
{
parent::__construct( $attributes );
$this->setEndpoint( '' );
}
public static function tweetsSearch( $query, $fromDate = null, $maxResults = 10 )
{
$parameters = [
'query' => $query,
'maxResults' => $maxResults,
'fromDate' => $fromDate,
];
return self::call( [ 'tweets/search/30day/testing.json' ], 'GET', $parameters );
}
}
使用预构建模型
<?php
namespace App\Models;
use MdelaRiva\ApiModel\Models\Twitter\User as TwitterUser;
class User extends TwitterUser
{
protected $connection = 'twitter';
}