sfadless/http

此包已被废弃且不再维护。未建议替代包。
此包的最新版本(2.0)没有可用的许可证信息。

用于获取/发送请求的小型库

2.0 2018-02-14 14:54 UTC

This package is auto-updated.

Last update: 2020-02-10 18:12:40 UTC


README

文档

安装

composer require Sfadless/http

用法

基本用法

use Sfadless\Utils\Http\Http;

require_once __DIR__ . '/vendor/autoload.php';

$http = new Http();

$response = $http->get('http://some.url');
$response = $http->post('http://some.url');

带有参数和头信息的用法

use Sfadless\Utils\Http\Http;

require_once __DIR__ . '/vendor/autoload.php';

$http = new Http();

$params = [
    'param1' => 'value',
    'param2' => 'value2'
];

$headers = [
    'header1' => 'value',
    'header2' => 'value'
];

$response = $http->post('http://some.url', $params, $headers);

请求和响应格式

默认情况下,响应值是字符串,请求值是数组。如果您的服务总是返回特定格式(例如 - json),您可以在构造函数中传递这些格式。

use Sfadless\Utils\Http\Http;
use Sfadless\Utils\Http\Format\Request\ArrayRequestFormat;
use Sfadless\Utils\Http\Format\Response\JsonResponseFormat;

$http = new Http(
    new ArrayRequestFormat(), //instanse of RequestFormatInterface, used by default
    new JsonResponseFormat(), //instanse of ResponseFormatInterface, response value will be passed throught getFormattedResponse method
);

您可以通过实现 RequestFormatInterface 和 ResponseFormatInterface 创建自己的请求和响应格式。在请求中,您应该创建 formatParams() 方法,其中将传递 $params(->post() 和 ->get() 方法的第二个参数),并返回用于流上下文选项的值。对于响应格式,您应该实现 getFormattedResponse() 方法,这是服务器响应与您的代码之间的层。