php - Can I add middleware to the default Guzzle 6 HandlerStack, rather than creating a new stack? -
i using spatie\crawler
crawler software in standard way, so:
$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);
i've omitted definition of classes mycrawlprofile
of mycrawlobserver
brevity, anyway, works stands.
i want add middleware in order change requests before made, added demo code:
$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 ...
however, falls on first hurdle - scrapes root of site (/
) location
redirect, , stops. turns out missing redirectmiddleware
despite not having removed deliberately.
so, problem fixed adding this:
$stack->push(middleware::redirect());
i wonder other things set default in guzzle have accidentally removed creating fresh handlerstack
. cookies? retry mechanisms? other stuff? don't need things right now, i'd bit more confident system's long-term reliability if code merely modified existing stack.
is there way that? far can tell, i'm doing things as per manual.
$stack = handlerstack::create();
instead of
$stack = new handlerstack(); $stack->sethandler(new curlhandler());
it's important, because create()
adds additional middlewares, redirects.
Comments
Post a Comment