### Install Guzzle via PEAR Source: https://github.com/guzzle/guzzle3/blob/master/docs/getting-started/installation.md Use PEAR commands to discover the channel and install the Guzzle package. ```bash pear channel-discover guzzlephp.org/pear pear install guzzle/guzzle ``` ```bash pear install guzzle/guzzle-3.9.0 ``` -------------------------------- ### Create and Send GET Requests Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/request.md Demonstrates creating a GET request with query parameters and headers, then sending it to retrieve a response. ```php use Guzzle\Http\Client; $client = new Client(); // Create a request that has a query string and an X-Foo header $request = $client->get('http://www.amazon.com?a=1', array('X-Foo' => 'Bar')); // Send the request and get the response $response = $request->send(); ``` -------------------------------- ### Implement a simple Echo plugin Source: https://github.com/guzzle/guzzle3/blob/master/docs/plugins/creating-plugins.md A complete example of a plugin class implementing EventSubscriberInterface to listen for the request.before_send event. ```php use Symfony\Component\EventDispatcher\EventSubscriberInterface; class EchoPlugin implements EventSubscriberInterface { public static function getSubscribedEvents() { return array('request.before_send' => 'onBeforeSend'); } public function onBeforeSend(Guzzle\Common\Event $event) { echo 'About to send a request: ' . $event['request'] . "\n"; } } $client = new Guzzle\Service\Client('http://www.test.com/'); // Create the plugin and add it as an event subscriber $plugin = new EchoPlugin(); $client->addSubscriber($plugin); // Send a request and notice that the request is printed to the screen $client->get('/')->send(); ``` -------------------------------- ### $client->get($uri, array $headers, $options) Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Creates a GET request. ```APIDOC ## $client->get($uri, array $headers, $options) ### Description Creates a GET request object. ### Parameters - **$uri** (string) - The URI for the request. - **$headers** (array) - An array of HTTP headers. - **$options** (array) - Additional request options. ``` -------------------------------- ### Instantiate a Guzzle Client and Send a Request Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Demonstrates creating a client with a base URL, sending a GET request with authentication, and accessing response data. ```php use Guzzle\Http\Client; // Create a client and provide a base URL $client = new Client('https://api.github.com'); $request = $client->get('/user'); $request->setAuth('user', 'pass'); echo $request->getUrl(); // >>> https://api.github.com/user // You must send a request in order for the transfer to occur $response = $request->send(); echo $response->getBody(); // >>> {"type":"User", ... echo $response->getHeader('Content-Length'); // >>> 792 $data = $response->json(); echo $data['type']; // >>> User ``` -------------------------------- ### Install Guzzle dependencies Source: https://github.com/guzzle/guzzle3/blob/master/docs/getting-started/installation.md Clones the repository and installs development dependencies using Composer. ```bash git clone https://github.com/guzzle/guzzle.git cd guzzle && curl -s http://getcomposer.org/installer | php && ./composer.phar install --dev ``` -------------------------------- ### Configure Response Download Location in PHP Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/request.md Examples for directing response body output to a file using request options or the setResponseBody method. ```php $request = $this->client->get('http://example.com/large.mov', array(), array( 'save_to' => '/tmp/large_file.mov' )); $request->send(); var_export(file_exists('/tmp/large_file.mov')); // >>> true ``` ```php $body = fopen('/tmp/large_file.mov', 'w'); $request = $this->client->get('http://example.com/large.mov'); $request->setResponseBody($body); // You can more easily specify the name of a file to save the contents // of the response to by passing a string to ``setResponseBody()``. $request = $this->client->get('http://example.com/large.mov'); $request->setResponseBody('/tmp/large_file.mov'); ``` -------------------------------- ### Install Bleeding Edge Version Source: https://github.com/guzzle/guzzle3/blob/master/docs/getting-started/installation.md Configure your composer.json to track the master branch for development. ```js { "require": { "guzzle/guzzle": "dev-master" } } ``` -------------------------------- ### Install Guzzle via Composer Source: https://github.com/guzzle/guzzle3/blob/master/README.md Commands to download Composer and add Guzzle 3 as a project dependency. ```bash # Install Composer curl -sS https://getcomposer.org/installer | php # Add Guzzle as a dependency php composer.phar require guzzle/guzzle:~3.9 ``` -------------------------------- ### Example JSON API Response Source: https://github.com/guzzle/guzzle3/blob/master/docs/iterators/resource-iterators.md Sample structure of a paginated response containing a list of users and a next token. ```javascript { "users": [ { "name": "Craig Johnson", "age": 10 }, { "name": "Tom Barker", "age": 20 }, { "name": "Bob Mitchell", "age": 74 } ], "next_user": "Michael Dowling" } ``` -------------------------------- ### Service Builder Configuration JSON Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/webservice-client.md Example JSON structure for defining services within a service builder configuration file. ```json { "services": { "twitter": { "class": "mtdowling\\TwitterClient", "params": { "consumer_key": "****", "consumer_secret": "****", "token": "****", "token_secret": "****" } } } } ``` -------------------------------- ### Install Guzzle Iterator via Composer Source: https://github.com/guzzle/guzzle3/blob/master/src/Guzzle/Iterator/README.md Commands to install Composer and add the Guzzle iterator package as a dependency. ```bash # Install Composer curl -sS https://getcomposer.org/installer | php # Add Guzzle as a dependency php composer.phar require guzzle/iterator:~3.0 ``` -------------------------------- ### GitHub API Request with Guzzle Source: https://github.com/guzzle/guzzle3/blob/master/docs/_templates/index.html Demonstrates creating a client, setting basic authentication, and sending a GET request to the GitHub API. ```php get('/user')->setAuth('user', 'pass'); // Send the request and get the response $response = $request->send(); echo $response->getBody(); // >>> {"type":"User", ... echo $response->getHeader('Content-Length'); // >>> 792 ``` -------------------------------- ### Guzzle Static Client Methods Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md The static client provides a facade for sending HTTP requests like GET and POST. Methods accept a URL and an optional array of request configuration options. ```APIDOC ## Static Client Methods ### Description Sends HTTP requests using the static facade. Supported methods include get(), post(), put(), etc. ### Parameters - **url** (string) - Required - The target URL. - **options** (array) - Optional - Associative array of request options (headers, body, timeout, etc.). ### Example ```php Guzzle::post('http://test.com', array( 'headers' => array('X-Foo' => 'Bar'), 'body' => array('Test' => '123'), 'timeout' => 10 )); ``` ``` -------------------------------- ### Configuring Client Options Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Demonstrates setting base URL variables, default headers, query parameters, authentication, and proxy settings during client instantiation. ```php use Guzzle\Http\Client; $client = new Client('https://api.twitter.com/{version}', array( 'version' => 'v1.1', 'request.options' => array( 'headers' => array('Foo' => 'Bar'), 'query' => array('testing' => '123'), 'auth' => array('username', 'password', 'Basic|Digest|NTLM|Any'), 'proxy' => 'tcp://localhost:80' ) )); ``` -------------------------------- ### Create and execute a command Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/webservice-client.md Demonstrates the standard flow of retrieving a command instance and triggering its execution. ```php // Get a command from the twitter client. $command = $twitter->getCommand('getMentions'); $result = $command->execute(); ``` -------------------------------- ### Use a Service Builder Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/webservice-client.md Initialize a service builder to manage client creation via a configuration file. ```php use Guzzle\Service\Builder\ServiceBuilder; // Create a service builder and provide client configuration data $builder = ServiceBuilder::factory('/path/to/client_config.json'); // Get the client from the service builder by name $twitter = $builder->get('twitter'); ``` -------------------------------- ### Initialize ServiceBuilder with a PHP file Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/using-the-service-builder.md Load a service configuration from a PHP file path. ```php $builder = ServiceBuilder::factory('/path/to/config.php'); ``` -------------------------------- ### Guzzle\Http\Client::get Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Creates a GET request using the Guzzle client, which can be sent to a remote server. ```APIDOC ## GET Request ### Description Creates a new GET request object using the client's base URL configuration. ### Method GET ### Parameters - **url** (string) - Required - The relative or absolute URL to request. ### Request Example $client->get('/user'); ### Response - **Guzzle\Http\Message\Request** - Returns a request object that can be configured and sent. ``` -------------------------------- ### Attach Service Description to Client Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/guzzle-service-descriptions.md Loads a service description file and executes a command using the configured client. ```php use Guzzle\Service\Description\ServiceDescription; $description = ServiceDescription::factory('/path/to/client.json'); $client->setDescription($description); $command = $client->getCommand('DeleteUser', array('id' => 123)); $responseModel = $client->execute($command); echo $responseModel['status']; ``` -------------------------------- ### Retrieve a client from the ServiceBuilder Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/using-the-service-builder.md Clients can be retrieved by their defined name using the get method or array access syntax. ```php $client = $builder->get('foo'); // You can also use the ServiceBuilder object as an array $client = $builder['foo']; ``` -------------------------------- ### Create a PHP configuration file Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/using-the-service-builder.md Define service configurations in a PHP file that returns an array to leverage opcode caching. ```php '...'); // Saved as config.php ``` -------------------------------- ### Configure client to use the test server Source: https://github.com/guzzle/guzzle3/blob/master/docs/testing/unit-testing.md Updates the client's base URL to point to the test server instance. ```php $client = $this->getServiceBuilder()->get('my_client'); $client->setBaseUrl($this->getServer()->getUrl()); ``` -------------------------------- ### Expand URI templates with client configuration Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/uri-templates.md Demonstrates automatic expansion of URI templates using variables defined in the client configuration. ```php $client = new Guzzle\\\Http\\\Client('https://example.com/', array('a' => 'hi')); $request = $client->get('/{a}'); ``` -------------------------------- ### Twitter API Integration with OAuth Source: https://github.com/guzzle/guzzle3/blob/master/docs/_templates/index.html Shows how to configure a client with the OauthPlugin and perform both GET and POST requests to the Twitter API. ```php '1.1' )); // Sign all requests with the OauthPlugin $client->addSubscriber(new Guzzle\Plugin\Oauth\OauthPlugin(array( 'consumer_key' => '***', 'consumer_secret' => '***', 'token' => '***', 'token_secret' => '***' ))); echo $client->get('statuses/user_timeline.json')->send()->getBody(); // >>> {"public_gists":6,"type":"User" ... // Create a tweet using POST $request = $client->post('statuses/update.json', null, array( 'status' => 'Tweeted with Guzzle, http://guzzlephp.org' )); // Send the request and parse the JSON response into an array $data = $request->send()->json(); echo $data['text']; // >>> Tweeted with Guzzle, http://t.co/kngJMfRk ``` -------------------------------- ### Run unit tests Source: https://github.com/guzzle/guzzle3/blob/master/docs/getting-started/installation.md Executes the test suite using the vendored PHPUnit binary. ```bash vendor/bin/phpunit ``` -------------------------------- ### Execute a command explicitly Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/webservice-client.md Create a command using getCommand, configure parameters, and execute it to retrieve the parsed response. ```php // Get a command from the client and pass an array of parameters $command = $twitter->getCommand('getMentions', array( 'count' => 5 )); // Other parameters can be set on the command after it is created $command['trim_user'] = false; // Execute the command using the command object. // The result value contains an array of JSON data from the response $result = $command->execute(); // You can retrieve the result of the command later too $result = $command->getResult(). ``` -------------------------------- ### Configure strict RFC redirect compliance Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/http-redirects.md Enables strict RFC compliance to prevent POST requests from being converted to GET requests during redirects. ```php // Set per request $request = $client->post(); $request->getParams()->set('redirect.strict', true); // You can set globally on a client so all requests use strict redirects $client->getConfig()->set('request.params', array( 'redirect.strict' => true )); ``` -------------------------------- ### Initialize ServiceBuilder from JSON Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/using-the-service-builder.md Create a ServiceBuilder instance by pointing to a JSON configuration file. ```php use Guzzle\Service\Builder\ServiceBuilder; // Source service definitions from a JSON file $builder = ServiceBuilder::factory('services.json'); ``` -------------------------------- ### Configure and use the CachePlugin Source: https://github.com/guzzle/guzzle3/blob/master/docs/plugins/cache-plugin.md Initializes the CachePlugin with a Doctrine filesystem cache adapter and attaches it to a Guzzle client. ```php use Guzzle\Http\Client; use Doctrine\Common\Cache\FilesystemCache; use Guzzle\Cache\DoctrineCacheAdapter; use Guzzle\Plugin\Cache\CachePlugin; use Guzzle\Plugin\Cache\DefaultCacheStorage; $client = new Client('http://www.test.com/'); $cachePlugin = new CachePlugin(array( 'storage' => new DefaultCacheStorage( new DoctrineCacheAdapter( new FilesystemCache('/path/to/cache/files') ) ) )); // Add the cache plugin to the client object $client->addSubscriber($cachePlugin); $client->get('http://www.wikipedia.org/')->send(); // The next request will revalidate against the origin server to see if it // has been modified. If a 304 response is received the response will be // served from cache $client->get('http://www.wikipedia.org/')->send(); ``` -------------------------------- ### Instantiating clients manually Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/using-the-service-builder.md Directly creating client instances using factory methods, which may lead to redundant configuration. ```php use MyService\FooClient; use MyService\BarClient; $foo = FooClient::factory(array( 'key' => 'abc', 'secret' => '123', 'custom' => 'and above all' )); $bar = BarClient::factory(array( 'key' => 'abc', 'secret' => '123', 'custom' => 'listen to me' )); ``` -------------------------------- ### Configure Request Options Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/request.md Pass configuration options like proxies directly when creating a request. ```php $request = $client->get($url, $headers, array('proxy' => 'http://proxy.com')); ``` -------------------------------- ### $client->head($uri, array $headers, $options) Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Creates a HEAD request. ```APIDOC ## $client->head($uri, array $headers, $options) ### Description Creates a HEAD request object. ### Parameters - **$uri** (string) - The URI for the request. - **$headers** (array) - An array of HTTP headers. - **$options** (array) - Additional request options. ``` -------------------------------- ### Execute commands with magic methods Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/webservice-client.md Use magic methods on the client to execute commands immediately and return the result. ```php $jsonData = $twitter->getMentions(array( 'count' => 5, 'trim_user' => true )); ``` -------------------------------- ### Create a throwaway client Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/using-the-service-builder.md Pass an array of configuration settings as the second argument to override defaults and prevent the client from being persisted by the ServiceBuilder. ```php // Get a throwaway client and overwrite the "custom" setting of the client $foo = $builder->get('foo', array( 'custom' => 'in this world there are rules' )); ``` -------------------------------- ### Instantiate a Twitter Client Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/webservice-client.md Directly instantiate a client using the factory method with required configuration credentials. ```php use mtdowling\TwitterClient; // Create a client and pass an array of configuration data $twitter = TwitterClient::factory(array( 'consumer_key' => '****', 'consumer_secret' => '****', 'token' => '****', 'token_secret' => '****' )); ``` -------------------------------- ### Instantiating clients with ServiceBuilder Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/using-the-service-builder.md Using the ServiceBuilder to centralize configuration and share parameters across multiple clients via inheritance. ```php use Guzzle\Service\Builder\ServiceBuilder; $builder = ServiceBuilder::factory(array( 'services' => array( 'abstract_client' => array( 'params' => array( 'key' => 'abc', 'secret' => '123' ) ), 'foo' => array( 'extends' => 'abstract_client', 'class' => 'MyService\FooClient', 'params' => array( 'custom' => 'and above all' ) ), 'bar' => array( 'extends' => 'abstract_client', 'class' => 'MyService\FooClient', 'params' => array( 'custom' => 'listen to me' ) ) ) )); $foo = $builder->get('foo'); $bar = $builder->get('bar'); ``` -------------------------------- ### Send requests with the static client Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Mount the static client to simplify sending HTTP requests. The static client methods accept an associative array of request options. ```php // Mount the client so that you can access it at \Guzzle Guzzle\Http\StaticClient::mount(); $response = Guzzle::get('http://guzzlephp.org'); ``` ```php $response = Guzzle::post('http://test.com', array( 'headers' => array('X-Foo' => 'Bar'), 'body' => array('Test' => '123'), 'timeout' => 10 )); ``` -------------------------------- ### Configure Zend Framework Cache Adapter Source: https://github.com/guzzle/guzzle3/blob/master/docs/plugins/cache-plugin.md Initializes a CachePlugin using the Zend Framework TestBackend. ```php use Guzzle\Cache\ZendCacheAdapter; use Zend\Cache\Backend\TestBackend; $backend = new TestBackend(); $adapter = new ZendCacheAdapter($backend); $cache = new CachePlugin($adapter); ``` -------------------------------- ### Registering and using the AsyncPlugin Source: https://github.com/guzzle/guzzle3/blob/master/docs/plugins/async-plugin.md Attaches the AsyncPlugin to a Guzzle client to enable asynchronous request behavior. ```php use Guzzle\Http\Client; use Guzzle\Plugin\Async\AsyncPlugin; $client = new Client('http://www.example.com'); $client->addSubscriber(new AsyncPlugin()); $response = $client->get()->send(); ``` -------------------------------- ### Define API Routes Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/guzzle-service-descriptions.md Lists the available HTTP methods and URI patterns for the Foo web service. ```default GET/POST /users GET/DELETE /users/:id ``` -------------------------------- ### Perform HTTP requests with Guzzle Source: https://github.com/guzzle/guzzle3/blob/master/docs/getting-started/overview.md Demonstrates both the static facade approach for simple requests and the client class approach for more granular control. ```php // Really simple using a static facade Guzzle\Http\StaticClient::mount(); $response = Guzzle::get('http://guzzlephp.org'); // More control using a client class $client = new \Guzzle\Http\Client('http://guzzlephp.org'); $request = $client->get('/'); $response = $request->send(); ``` -------------------------------- ### $client->post($uri, array $headers, $postBody, $options) Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Creates a POST request. ```APIDOC ## $client->post($uri, array $headers, $postBody, $options) ### Description Creates a POST request object. ### Parameters - **$uri** (string) - The URI for the request. - **$headers** (array) - An array of HTTP headers. - **$postBody** (mixed) - The POST body. - **$options** (array) - Additional request options. ``` -------------------------------- ### Create and use a command transfer batch Source: https://github.com/guzzle/guzzle3/blob/master/docs/batching/batching.md Initializes a batch object for service commands and demonstrates adding and flushing commands. ```php use Guzzle\Batch\BatchBuilder; $batch = BatchBuilder::factory() ->transferCommands(10) ->build(); $batch->add($client->getCommand('foo')) ->add($client->getCommand('baz')) ->add($client->getCommand('bar')); $commands = $batch->flush(); ``` -------------------------------- ### Initialize Twitter Widget Source: https://github.com/guzzle/guzzle3/blob/master/docs/_templates/index.html Standard script for loading the Twitter widget library asynchronously. ```javascript !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="http://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); ``` -------------------------------- ### Define services using JSON Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/using-the-service-builder.md Serialize service descriptions using JSON format with the same structure as PHP arrays. ```json { "includes": ["/path/to/other/services.json", "/path/to/other/php_services.php"], "services": { "abstract.foo": { "params": { "username": "foo", "password": "bar" } }, "bar": { "extends": "abstract.foo", "class": "MyClientClass", "params": { "other": "abc" } } } } ``` -------------------------------- ### Migrate LogPlugin and Log Adapters Source: https://github.com/guzzle/guzzle3/blob/master/UPGRADING.md Update namespaces for LogPlugin and log adapters, and switch from verbosity integers to format strings. ```php use Guzzle\Common\Log\ClosureLogAdapter; use Guzzle\Http\Plugin\LogPlugin; /** @var \Guzzle\Http\Client */ $client; // $verbosity is an integer indicating desired message verbosity level $client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $verbosity = LogPlugin::LOG_VERBOSE); ``` ```php use Guzzle\Log\ClosureLogAdapter; use Guzzle\Log\MessageFormatter; use Guzzle\Plugin\Log\LogPlugin; /** @var \Guzzle\Http\Client */ $client; // $format is a string indicating desired message format -- @see MessageFormatter $client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT); ``` -------------------------------- ### Send an OPTIONS request Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/request.md Requests communication options for a resource and checks supported methods. ```php $request = $client->options('http://httpbin.org'); $response = $request->send(); // Check if the PUT method is supported by this resource var_export($response->isMethodAllows('PUT')); ``` -------------------------------- ### Stream with Static Client Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/response.md Use the stream option to simplify streaming response handling. ```php $stream = Guzzle::get('http://guzzlephp.org', array('stream' => true)); while (!$stream->feof()) { echo $stream->readLine(); } ``` -------------------------------- ### Set default command parameters Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/webservice-client.md Pass default key-value pairs to all commands created by the client via the command.params configuration. ```php $client = new Guzzle Service Client(array( 'command.params' => array( 'default_1' => 'foo', 'another' => 'bar' ) )); ``` -------------------------------- ### Configure query string parameters Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Define query parameters for specific requests or set defaults on the client instance. ```php $request = $client->get($url, array(), array( 'query' => array('abc' => '123') )); ``` ```php $client = new Guzzle\Http\Client(); // Set a single query string parameter using path syntax $client->setDefaultOption('query/abc', '123'); // Set an array of default query string parameters $client->setDefaultOption('query', array('abc' => '123')); ``` -------------------------------- ### Creating and sending HTTP requests with Guzzle Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Demonstrates creating various HTTP request types using a base URL and sending them to receive a response. ```php use Guzzle\Http\Client; $client = new Client('http://baseurl.com/api/v1'); // Create a GET request using Relative to base URL // URL of the request: http://baseurl.com/api/v1/path?query=123&value=abc) $request = $client->get('path?query=123&value=abc'); $response = $request->send(); // Create HEAD request using a relative URL with an absolute path // URL of the request: http://baseurl.com/path?query=123&value=abc $request = $client->head('/path?query=123&value=abc'); $response = $request->send(); // Create a DELETE request using an absolute URL $request = $client->delete('http://www.example.com/path?query=123&value=abc'); $response = $request->send(); // Create a PUT request using the contents of a PHP stream as the body // Specify custom HTTP headers $request = $client->put('http://www.example.com/upload', array( 'X-Header' => 'My Header' ), fopen('http://www.test.com/', 'r')); $response = $request->send(); // Create a POST request and add the POST files manually $request = $client->post('http://localhost:8983/solr/update') ->addPostFiles(array('file' => '/path/to/documents.xml')); $response = $request->send(); // Check if a resource supports the DELETE method $supportsDelete = $client->options('/path')->send()->isMethodAllowed('DELETE'); $response = $request->send(); ``` -------------------------------- ### Configure request headers Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Set headers for individual requests or define default headers for all requests sent by a client instance. ```php $request = $client->get($url, array(), array( 'headers' => array('X-Foo' => 'Bar') )); ``` ```php $client = new Guzzle\Http\Client(); // Set a single header using path syntax $client->setDefaultOption('headers/X-Foo', 'Bar'); // Set all headers $client->setDefaultOption('headers', array('X-Foo' => 'Bar')); ``` ```php $client->getConfig()->setPath('request.options/headers/X-Foo', 'Bar'); ``` -------------------------------- ### Listen to client.create_request events Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Attach a listener to the client's event dispatcher to execute logic whenever a new request is created. ```php use Guzzle\Common\Event; use Guzzle\Http\Client; $client = new Client(); // Add a listener that will echo out requests as they are created $client->getEventDispatcher()->addListener('client.create_request', function (Event $e) { echo 'Client object: ' . spl_object_hash($e['client']) . "\n"; echo "Request object: {$e['request']}\n"; }); ``` -------------------------------- ### Create and Send HEAD Requests Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/request.md Retrieves meta information about a resource without downloading the full entity body. ```php $client = new Guzzle\Http\Client(); $request = $client->head('http://www.amazon.com'); $response = $request->send(); echo $response->getContentLength(); // >>> Will output the Content-Length header value ``` -------------------------------- ### Iterate over web service resources Source: https://github.com/guzzle/guzzle3/blob/master/docs/iterators/resource-iterators.md Use the getIterator method on a client to retrieve all resources for a command, abstracting the underlying pagination logic. ```php $iterator = $client->getIterator('get_users'); foreach ($iterator as $user) { echo $user['name'] . ' age ' . $user['age'] . PHP_EOL; } ``` -------------------------------- ### Build a POST request fluently Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/request.md Constructs a POST request using method chaining for fields and files. ```php $request = $client->post('http://httpbin.org/post') ->setPostField('custom_field', 'my custom value') ->addPostFile('file', '/path/to/file.xml'); $response = $request->send(); ``` -------------------------------- ### Implementing a ResourceIterator Class Source: https://github.com/guzzle/guzzle3/blob/master/docs/iterators/resource-iterators.md Custom implementation of ResourceIterator that handles command execution and token-based pagination. ```php namespace MyService\Model; use Guzzle\Service\Resource\ResourceIterator; /** * Iterate over a get_users command */ class GetUsersIterator extends ResourceIterator { protected function sendRequest() { // If a next token is set, then add it to the command if ($this->nextToken) { $this->command->set('next_user', $this->nextToken); } // Execute the command and parse the result $result = $this->command->execute(); // Parse the next token $this->nextToken = isset($result['next_user']) ? $result['next_user'] : false; return $result['users']; } } ``` -------------------------------- ### Configure Doctrine Cache Adapter Source: https://github.com/guzzle/guzzle3/blob/master/docs/plugins/cache-plugin.md Initializes a CachePlugin using the Doctrine ArrayCache backend. ```php use Doctrine\Common\Cache\ArrayCache; use Guzzle\Cache\DoctrineCacheAdapter; use Guzzle\Plugin\Cache\CachePlugin; $backend = new ArrayCache(); $adapter = new DoctrineCacheAdapter($backend); $cache = new CachePlugin($adapter); ``` -------------------------------- ### Attach Service Description to Client Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/webservice-client.md Implementation of the factory method to register the service description with the Guzzle client. ```php // ... class TwitterClient extends Client { public static function factory($config = array()) { // ... same code as before ... // Set the service description $client->setDescription(ServiceDescription::factory('path/to/twitter.json')); return $client; } } ``` -------------------------------- ### Configure SSL client certificates Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Specify a PEM formatted certificate file path, optionally including a password as the second array element. ```php $request = $client->get('https://www.example.com', array(), array( 'cert' => '/etc/pki/client_certificate.pem' ) $request = $client->get('https://www.example.com', array(), array( 'cert' => array('/etc/pki/client_certificate.pem', 's3cr3tp455w0rd') ) ``` -------------------------------- ### Reference clients in JSON parameters Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/using-the-service-builder.md Inject one client into another by enclosing the reference key in curly braces. ```json { "services": { "token": { "class": "My\Token\TokenFactory", "params": { "access_key": "xyz" } }, "client": { "class": "My\Client", "params": { "token_client": "{token}", "version": "1.0" } } } } ``` -------------------------------- ### Define Service Configuration Array Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/using-the-service-builder.md Structure an associative array to define services, including includes and client-specific parameters. ```php $services = array( 'includes' => array( '/path/to/other/services.json', '/path/to/other/php_services.php' ), 'services' => array( 'abstract.foo' => array( 'params' => array( 'username' => 'foo', 'password' => 'bar' ) ), 'bar' => array( 'extends' => 'abstract.foo', 'class' => 'MyClientClass', 'params' => array( 'other' => 'abc' ) ) ) ); ``` -------------------------------- ### Retrieve raw configuration settings Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/using-the-service-builder.md Use the getData method to access the original configuration array for a specific service definition. ```php $data = $builder->getData('foo'); echo $data['key'] . "\n"; echo $data['secret'] . "\n"; echo $data['custom'] . "\n"; ``` -------------------------------- ### Configure and attach LogPlugin to a client Source: https://github.com/guzzle/guzzle3/blob/master/docs/plugins/log-plugin.md Initializes a LogPlugin with a Zend_Log adapter and attaches it to a Guzzle client to log all outgoing requests. ```php use Guzzle\Http\Client; use Guzzle\Log\Zf1LogAdapter; use Guzzle\Plugin\Log\LogPlugin; use Guzzle\Log\MessageFormatter; $client = new Client('http://www.test.com/'); $adapter = new Zf1LogAdapter( new \Zend_Log(new \Zend_Log_Writer_Stream('php://output')) ); $logPlugin = new LogPlugin($adapter, MessageFormatter::DEBUG_FORMAT); // Attach the plugin to the client, which will in turn be attached to all // requests generated by the client $client->addSubscriber($logPlugin); $response = $client->get('http://google.com')->send(); ``` -------------------------------- ### Customizing User-Agent Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Shows how to either completely replace or prepend a string to the default Guzzle User-Agent header. ```php // Completely override the default User-Agent $client->setUserAgent('Test/123'); // Prepend a string to the default User-Agent $client->setUserAgent('Test/123', true); ``` -------------------------------- ### Listening to service builder events Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/using-the-service-builder.md Registers an event listener to the service builder to monitor client creation. ```php use Guzzle\\Common\\Event; use Guzzle\\Service\\Builder\\ServiceBuilder; $builder = ServiceBuilder::factory('/path/to/config.json'); // Add an event listener to print out each client client as it is created $builder->getEventDispatcher()->addListener('service_builder.create_client', function (Event $e) { echo 'Client created: ' . get_class($e['client']) . "\n"; }); $foo = $builder->get('foo'); // Should output the class used for the "foo" client ``` -------------------------------- ### Configure SSL private keys Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Specify a PEM formatted private key file path, optionally including a password as the second array element. ```php $request = $client->get('https://www.example.com', array(), array( 'ssl_key' => '/etc/pki/private_key.pem' ) $request = $client->get('https://www.example.com', array(), array( 'ssl_key' => array('/etc/pki/private_key.pem', 's3cr3tp455w0rd') ) ``` -------------------------------- ### Implement a custom command class for Twitter API Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/webservice-client.md Extends AbstractCommand to manually build a request and serialize parameters into the query string. ```php namespace mtdowling\Twitter\Command; use Guzzle\Service\Command\AbstractCommand; class GetMentions extends AbstractCommand { protected function build() { // Create the request property of the command $this->request = $this->client->get('statuses/mentions_timeline.json'); // Grab the query object of the request because we will use it for // serializing command parameters on the request $query = $this->request->getQuery(); if ($this['count']) { $query->set('count', $this['count']); } if ($this['since_id']) { $query->set('since_id', $this['since_id']); } if ($this['max_id']) { $query->set('max_id', $this['max_id']); } if ($this['trim_user'] !== null) { $query->set('trim_user', $this['trim_user'] ? 'true' : 'false'); } if ($this['contributor_details'] !== null) { $query->set('contributor_details', $this['contributor_details'] ? 'true' : 'false'); } if ($this['include_entities'] !== null) { $query->set('include_entities', $this['include_entities'] ? 'true' : 'false'); } } } ``` -------------------------------- ### Configure and use the History plugin Source: https://github.com/guzzle/guzzle3/blob/master/docs/plugins/history-plugin.md Attach the plugin to a Guzzle client to track requests and responses. The limit can be adjusted using setLimit, and history data is accessible via methods like getLastRequest and count. ```php use Guzzle\Http\Client; use Guzzle\Plugin\History\HistoryPlugin; $client = new Client('http://www.test.com/'); // Add the history plugin to the client object $history = new HistoryPlugin(); $history->setLimit(5); $client->addSubscriber($history); $client->get('http://www.yahoo.com/')->send(); echo $history->getLastRequest(); echo $history->getLastResponse(); echo count($history); ``` -------------------------------- ### Adding a global plugin to a service builder Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/using-the-service-builder.md Attaches a plugin to every client created by the service builder instance. ```php use Guzzle\\\\ ``` ```php use Guzzle\\Plugin\\Log\\LogPlugin; // Add a debug log plugin to every client as it is created $builder->addGlobalPlugin(LogPlugin::getDebugPlugin()); $foo = $builder->get('foo'); $foo->get('/')->send(); // Should output all of the data sent over the wire ``` -------------------------------- ### Implement an event subscriber for a Service Client Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/webservice-client.md Defines a class implementing EventSubscriberInterface to handle multiple client events, then registers it with the client. ```php use Guzzle\Common\Event; use Guzzle\Common\Client; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class EventSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( 'client.command.create' => 'onCommandCreate', 'command.parse_response' => 'onParseResponse' ); } public function onCommandCreate(Event $event) { $client = $event['client']; $command = $event['command']; // operate on client and command } public function onParseResponse(Event $event) { $command = $event['command']; // operate on the command } } $client = new Client(); $client->addSubscriber(new EventSubscriber()); ``` -------------------------------- ### Execute commands using magic methods Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/webservice-client.md Invoke commands directly as methods on the client object, which internally maps to the getCommand().execute() workflow. ```php // Use the magic method $result = $twitter->getMentions(); // This is exactly the same as: $result = $twitter->getCommand('getMentions')->execute(); ``` -------------------------------- ### Add an event listener to a Service Client Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/webservice-client.md Attaches a callback function to the 'command.after_prepare' event to modify request objects. ```php use Guzzle\Common\Event; use Guzzle\Service\Client; $client = new Client(); // create an event listener that operates on request objects $client->getEventDispatcher()->addListener('command.after_prepare', function (Event $event) { $command = $event['command']; $request = $command->getRequest(); // do something with request }); ``` -------------------------------- ### Attach plugins to a request Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Use the plugins option to register an array of plugins with a static Guzzle request. ```php // Using the static client: Guzzle::get($url, array( 'plugins' => array( new Guzzle\Plugin\Cache\CachePlugin(), new Guzzle\Plugin\Cookie\CookiePlugin() ) )); ``` -------------------------------- ### Implement a Custom Client Factory Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/webservice-client.md Define a client class that extends Guzzle\Service\Client and implements a static factory method to handle configuration, validation, and plugin attachment. ```php namespace mtdowling; use Guzzle\Common\Collection; use Guzzle\Plugin\Oauth\OauthPlugin; use Guzzle\Service\Client; use Guzzle\Service\Description\ServiceDescription; /** * A simple Twitter API client */ class TwitterClient extends Client { public static function factory($config = array()) { // Provide a hash of default client configuration options $default = array('base_url' => 'https://api.twitter.com/1.1'); // The following values are required when creating the client $required = array( 'base_url', 'consumer_key', 'consumer_secret', 'token', 'token_secret' ); // Merge in default settings and validate the config $config = Collection::fromConfig($config, $default, $required); // Create a new Twitter client $client = new self($config->get('base_url'), $config); // Ensure that the OauthPlugin is attached to the client $client->addSubscriber(new OauthPlugin($config->toArray())); return $client; } } ``` -------------------------------- ### Implement a custom ResponseClassInterface Source: https://github.com/guzzle/guzzle3/blob/master/docs/webservice-client/guzzle-service-descriptions.md Create a class that implements ResponseClassInterface to transform command responses into domain model objects. ```php namespace MyApplication; use Guzzle\ Service\Command\ResponseClassInterface; use Guzzle\Service\Command\OperationCommand; class User implements ResponseClassInterface { protected $name; public static function fromCommand(OperationCommand $command) { $response = $command->getResponse(); $xml = $response->xml(); return new self((string) $xml->name); } public function __construct($name) { $this->name = $name; } } ``` -------------------------------- ### $client->put($uri, array $headers, $body, $options) Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/client.md Creates a PUT request. ```APIDOC ## $client->put($uri, array $headers, $body, $options) ### Description Creates a PUT request object. ### Parameters - **$uri** (string) - The URI for the request. - **$headers** (array) - An array of HTTP headers. - **$body** (mixed) - The request body. - **$options** (array) - Additional request options. ``` -------------------------------- ### Enqueue a response in the test server Source: https://github.com/guzzle/guzzle3/blob/master/docs/testing/unit-testing.md Queues a raw HTTP response string to be returned by the test server in FIFO order. ```php $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); ``` -------------------------------- ### Mock HTTP Response File Format Source: https://github.com/guzzle/guzzle3/blob/master/docs/testing/unit-testing.md Mock response files must contain a full HTTP response message including headers and body content. ```none HTTP/1.1 200 OK Date: Wed, 25 Nov 2009 12:00:00 GMT Connection: close Server: AmazonS3 Content-Type: application/xml EU ``` -------------------------------- ### Manipulate and send an entity body Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/entity-bodies.md Demonstrates creating an EntityBody from a file resource, performing read/write operations, and attaching it to a PUT request. ```php use Guzzle\Http\EntityBody; $body = EntityBody::factory(fopen('/path/to/file.txt', 'r+')); echo $body->read(1024); $body->seek(0, SEEK_END); $body->write('foo'); echo $body->ftell(); $body->rewind(); // Send a request using the body $response = $client->put('http://localhost:8080/uploads', null, $body)->send(); ``` -------------------------------- ### Attach a HistoryPlugin to a Guzzle Client Source: https://github.com/guzzle/guzzle3/blob/master/docs/plugins/plugins-overview.md Demonstrates attaching a HistoryPlugin to a client instance so that all subsequent requests sent by the client are tracked. ```php use Guzzle\Plugin\History\HistoryPlugin; use Guzzle\Service\Client; $client = new Client(); // Create a history plugin and attach it to the client $history = new HistoryPlugin(); $client->addSubscriber($history); // Create and send a request. This request will also utilize the HistoryPlugin $client->get('http://httpbin.org')->send(); // Echo out the last sent request by the client echo $history->getLastRequest(); ``` -------------------------------- ### Managing HTTP Request Headers in Guzzle 3 Source: https://github.com/guzzle/guzzle3/blob/master/docs/http-client/request.md Demonstrates adding, setting, retrieving, and iterating over request headers using Guzzle 3 methods. ```php $request = new Request('GET', 'http://httpbin.com/cookies'); // addHeader will set and append to any existing header values $request->addHeader('Foo', 'bar'); $request->addHeader('foo', 'baz'); // setHeader overwrites any existing values $request->setHeader('Test', '123'); // Request headers can be cast as a string echo $request->getHeader('Foo'); // >>> bar, baz echo $request->getHeader('Test'); // >>> 123 // You can count the number of headers of a particular case insensitive name echo count($request->getHeader('foO')); // >>> 2 // You can iterate over Header objects foreach ($request->getHeader('foo') as $header) { echo $header . "\n"; } // You can get all of the request headers as a Guzzle\Http\Message\Header\HeaderCollection object $headers = $request->getHeaders(); // Missing headers return NULL var_export($request->getHeader('Missing')); // >>> null // You can see all of the different variations of a header by calling raw() on the Header var_export($request->getHeader('foo')->raw()); ``` -------------------------------- ### Migrate ServiceDescription Commands to Operations Source: https://github.com/guzzle/guzzle3/blob/master/UPGRADING.md Update service description method calls from command-based terminology to operation-based terminology. ```php use Guzzle\Service\Description\ServiceDescription; $sd = new ServiceDescription(); $sd->getCommands(); // @returns ApiCommandInterface[] $sd->hasCommand($name); $sd->getCommand($name); // @returns ApiCommandInterface|null $sd->addCommand($command); // @param ApiCommandInterface $command ``` ```php use Guzzle\Service\Description\ServiceDescription; $sd = new ServiceDescription(); $sd->getOperations(); // @returns OperationInterface[] $sd->hasOperation($name); $sd->getOperation($name); // @returns OperationInterface|null $sd->addOperation($operation); // @param OperationInterface $operation ```