half2me/curlx

此包已被废弃,不再维护。作者建议使用 guzzlehttp/guzzle 包。

cUrl Multi 的易用封装器

1.0.0 2016-02-12 22:24 UTC

This package is auto-updated.

Last update: 2020-02-26 10:08:02 UTC


README

Software License Build Status Scrutinizer Code Quality codecov.io Total Downloads Latest Stable Version Latest Unstable Version
Curl X 是 RollingCurlX 的分支,地址为 https://github.com/marcushat/RollingCurlX。最初我创建这个分支是为了使我正在工作的项目可以通过 composer 安装。现在,它是一个现代化、易用、出色的 cUrl Multi Handler 封装器。有了代理和请求,看看一切变得多么简单。

####许可证 MIT

需求

PHP 5.6+

安装

使用 composer 安装很简单。只需执行 composer require half2me/curlx:^1.0

##如何使用

首先,我们初始化一个代理,指定我们希望一次打开的最大并发请求数。在此之后的所有请求都将排队,直到其中一个完成。

use CurlX\Agent;

$agent = new Agent(10);

接下来,我们将创建/添加一个请求到队列中

$request = $agent->newRequest('http://myurl.com'); // URL can optionally be set here
$request->url = 'http://myurl.com'; // or here
$request->timeout = 5000; // We can set different timeout values (in msec) for each request
$request->post_data = ['Agents' => 'AreCool']; // We can add post fields as arrays
$request->post_data = ['MoreAgents' => 'AreCooler']; // This will be appended to the post values already set
$request->headers = ['Content-type' => 'agent/xml', 'Authorization' => 'ninja-stuff']; // Headers can easily be set
$request->headers = ['Agent-type: Ninja']; // These will be appended to the header list
$request->options = ['CURLOPT_SOME_OPTION' => 'your-value']; // Advanced options can be set for cURL
$request->options = ['CURLOPT_SOME_OTHER_OPTION' => 'your-other-value']; // Chain these up, or add many in one array

// The Agent already has this request in his queue, so we don't need to do anything after modifying requests options.

大多数可以设置在单个请求上的值也可以设置在代理上。当一个代理设置了这些值时,该代理创建的任何请求都将设置这些参数;如果我们有很多使用类似头、url 或超时值的请求,我们可以在代理中设置一次,并在所有请求中使用它们。例如

$agent->post_data = ['AllAgents' => 'AreCool'];
$request = $agent->newRequest();

echo $request->post_data['AllAgents']; // this will output 'AreCool'

// of course we can always overwrite this:
$request->post_data = ['AllAgents' => 'AreSuperDuperCool']; // This will overwrite that post value

一旦我们将请求加载到代理中

$request1 = $agent->newRequest();
$request2 = $agent->newRequest();

我们可以开始执行它们

$agent->execute();

随着请求的完成,它将触发一个事件,我们需要在启动代理之前将其挂钩。为此,我们需要使用代理(用于所有请求)或为每个请求注册一个单独的回调函数注册一个或多个回调函数。

$request1->addListener('myCallbackFunction'); // For a single request
$agent->addListener('myCallbackFunction'); // For all requests to use the same callback
// Note, this will only apply to requests made after the addListener() was called.

// You can use anonymous functions for callbacks like this:
$request->addListener(function(CurlX\RequestInterface $request) {
    // Each listener (or callback function) will upon request completion receieve
    // in the function parameter, the completed request object
    
    echo $request->response; // Response is stored here
    echo $request->http_code; // Get the http code of the reply
});

问题

如果你发现任何问题,请告诉我。在 github 上提交问题或 PR

享受吧。