我可以将中间件添加到默认的 Guzzle 6 HandlerStack,而不是创建新堆栈吗?

Can I add middleware to the default Guzzle 6 HandlerStack, rather than creating a new stack?

我正在以相当标准的方式使用 Spatie\Crawler 爬虫软件,例如:

$client = new Client([
    RequestOptions::COOKIES => true,
    RequestOptions::CONNECT_TIMEOUT => 10,
    RequestOptions::TIMEOUT => 10,
    RequestOptions::ALLOW_REDIRECTS => true,
]);
$crawler = new Crawler($client, 1);
$crawler->
    setCrawlProfile(new MyCrawlProfile($startUrl, $pathRegex))->
    setCrawlObserver(new MyCrawlObserver())->
    startCrawling($url);

为简洁起见,我省略了 MyCrawlObserver 的 类 MyCrawlProfile 的定义,但无论如何,它按原样工作。

我想添加一些中间件以便在发出请求之前更改一些请求,所以我添加了这个演示代码:

$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(
    Middleware::mapRequest(function (RequestInterface $request) {
        echo "Middleware running\n";

        return $request;
    })
);
$client = new Client([
    RequestOptions::COOKIES => true,
    RequestOptions::CONNECT_TIMEOUT => 10,
    RequestOptions::TIMEOUT => 10,
    RequestOptions::ALLOW_REDIRECTS => true,
    'handler' => $stack,
]);
// ... rest of crawler code here ...

然而,它遇到了第一个障碍 - 它抓取了网站的根目录 (/),这实际上是一个 Location 重定向,然后停止。事实证明,尽管我没有故意删除它,但我现在错过了 RedirectMiddleware

所以,我的问题也通过添加以下内容得到解决:

$stack->push(Middleware::redirect());

我现在想知道 Guzzle 中还有哪些默认设置是我通过创建新 HandlerStack 不小心删除的。饼干?重试机制?其他的东西?我现在不需要这些东西,但如果我的代码只是修改现有堆栈,我会对系统的长期可靠性更有信心。

有办法吗?据我所知,我正在做 as per the manual.

$stack = HandlerStack::create();

而不是

$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());

这很重要,因为 create() 添加了额外的中间件,尤其是对于重定向。