戴夫K1312 / apiintegrator
v0.8.1
2017-07-08 23:36 UTC
Requires
- davek1312/serialise: 0.3.*
- davek1312/variableutils: 0.*
- guzzlehttp/guzzle: ^6.2
Requires (Dev)
- phpunit/phpunit: ~4.0
README
从第三方API检索数据并将其反序列化为PHP模型。
安装
该软件包可在Packagist上找到,您可以使用Composer进行安装。
composer require davek1312/apiintegrator
配置
响应模型
构建您的响应模型类。使用JMS注解注解您的模型。您的模型应具有与API响应相同的属性。您的响应模型还定义了API响应的数据类型。
use JMS\Serializer\Annotation\Exclude;
class YourResponseModel extends Davek1312\ApiIntegrator\Models\ApiIntegratorResponseModel {
/**
* @Type("string")
*/
private $apiProperty;
/**
* The API's response format: 'json' OR 'xml'
*
* @return string
*/
public static function getResponseDataType() {
return 'json';
}
public function getApiProperty() {
return $this->apiProperty;
}
}
如果API响应包含错误属性,则响应模型类应重写基本响应错误访问器
use JMS\Serializer\Annotation\Type;
class YourResponseModel extends Davek1312\ApiIntegrator\Models\ApiIntegratorResponseModel {
/**
* @Type("string")
*/
private $apiErrorMessage;
/**
* @Type("integer")
*/
private $apiErrorCode;
public function getResponseErrorMessage() {
return $this->apiErrorMessage;
}
public function getResponseErrorCode() {
return $this->apiErrorCode;
}
}
集成器
您的集成器必须扩展基本集成器并定义上面创建的$responseModelClass
use YourResponseModel;
class YourIntegrator extends Davek1312\ApiIntegrator\ApiIntegrator {
/**
* @var string
*/
public static $responseModelClass = YourResponseModel::class;
}
使用方法
构建您的请求模型
/*
* $url(string): The API's url
* $connectionMethod(string): The HTTP connection method e.g. GET, POST, DELETE etc.
* $connectTimeout(double): Seconds allowed to establish a connection to the API
* $requestTimeout(double): Seconds allowed to complete request
* $additionalRequestOptions(array): An optional array of request options from http://docs.guzzlephp.org/en/latest/request-options.html
*/
$requestModel = new ApiIntegratorRequestModel($url, $connectionMethod, $connectTimeout, $requestTimeout, array $additionalRequestOptions = []);
使用您的集成器生成响应模型
$integrator = new YourIntegrator($requestModel);
$responseModel = $integrator->generateNewResponseModel();
检查错误
if($integrator->hasErrors()) {
$errorModel = $integrator->getErrorModel();
}