Created
January 15, 2012 16:49
-
-
Save mtdowling/1616395 to your computer and use it in GitHub Desktop.
Guzzle: async curl requests with mocked responses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include 'guzzle.phar'; | |
use Guzzle\Http\Client; | |
use Guzzle\Http\Message\Response; | |
use Guzzle\Http\Plugin\BatchQueuePlugin; | |
use Guzzle\Http\Plugin\MockPlugin; | |
$client = new Client('http://www.test.com/'); | |
// Create a new batch queue plugin. Any reqeust created by a client will be | |
// automatically tracked and queued by the BatchQueuePlugin. You can specify | |
// the maximum amount of requests to keep in queue before implicitly flushing, | |
// or set 0 to never automatically flush. Here we are saying that if 10 or | |
// more requests are in the batch queue, then it must automatically flush the | |
// queue and send the requests. | |
$batchPlugin = new BatchQueuePlugin(10); | |
// Create a mock plugin that will satisfy requests using mock responses | |
// Mock requests will be removed from the mock queue as requests are | |
// sent by an attached client | |
$mockPlugin = new MockPlugin(array( | |
new Response(200), | |
new Response(201), | |
new Response(202), | |
)); | |
// Add the batch plugin to the client object | |
$client->getEventDispatcher()->addSubscriber($batchPlugin); | |
// Add the mock plugin to the client object so that requests are mocked | |
$client->getEventDispatcher()->addSubscriber($mockPlugin); | |
// Queue up some requests on the BatchQueuePlugin | |
$request1 = $client->get('/'); | |
$request2 = $client->get('/'); | |
$request3 = $client->get('/'); | |
// If the batch plugin is handy, you can call the flush method directly | |
$batchPlugin->flush(); | |
// If you no longer have the batch plugin handy, you can emit the 'flush' event | |
// from the client | |
$client->dispatch('flush'); | |
// Now the requests have been sent and have been served a mock response | |
echo $request1->getResponse(); | |
echo $request2->getResponse(); | |
echo $request3->getResponse(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment