PHPackages                             guzzlehttp/command - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. guzzlehttp/command

ActiveLibrary[HTTP &amp; Networking](/categories/http)

guzzlehttp/command
==================

Provides the foundation for building command-based web service clients

1.5.1(1w ago)11611.2M↓47.5%2119MITPHPPHP ^7.2.5 || ^8.0CI passing

Since Mar 16Pushed 1w ago9 watchersCompare

[ Source](https://github.com/guzzle/command)[ Packagist](https://packagist.org/packages/guzzlehttp/command)[ GitHub Sponsors](https://github.com/GrahamCampbell)[ GitHub Sponsors](https://github.com/Nyholm)[ RSS](/packages/guzzlehttp-command/feed)WikiDiscussions 1.5 Synced yesterday

READMEChangelog (10)Dependencies (16)Versions (57)Used By (19)

Guzzle Commands
===============

[](#guzzle-commands)

This library uses Guzzle and provides the foundations to create fully-featured web service clients by abstracting Guzzle HTTP *requests* and *responses* into higher-level *commands* and *results*. A *middleware* system, analogous to, but separate from, the one in the HTTP layer may be used to customize client behavior when preparing commands into requests and processing responses into results.

### Commands

[](#commands)

Key-value pair objects representing an operation of a web service. Commands have a name and a set of parameters.

### Results

[](#results)

Key-value pair objects representing the processed result of executing an operation of a web service.

Installing
----------

[](#installing)

This project can be installed using [Composer](https://getcomposer.org/):

```
composer require guzzlehttp/command

```

Service Clients
---------------

[](#service-clients)

Service Clients are web service clients that implement the `GuzzleHttp\Command\ServiceClientInterface` and use an underlying Guzzle HTTP client (`GuzzleHttp\ClientInterface`) to communicate with the service. Service clients create and execute *commands* (`GuzzleHttp\Command\CommandInterface`), which encapsulate operations within the web service, including the operation name and parameters. This library provides a generic implementation of a service client: the `GuzzleHttp\Command\ServiceClient` class.

Instantiating a Service Client
------------------------------

[](#instantiating-a-service-client)

The provided service client implementation (`GuzzleHttp\Command\ServiceClient`) can be instantiated by providing the following arguments:

1. A fully-configured Guzzle HTTP client that will be used to perform the underlying HTTP requests. That is, an instance of an object implementing `GuzzleHttp\ClientInterface` such as `new GuzzleHttp\Client()`.
2. A callable that transforms a Command into a Request. The function should accept a `GuzzleHttp\Command\CommandInterface` object and return a `Psr\Http\Message\RequestInterface` object.
3. A callable that transforms a Response into a Result. The function should accept a `Psr\Http\Message\ResponseInterface` object and optionally a `Psr\Http\Message\RequestInterface` object, and return a `GuzzleHttp\Command\ResultInterface` object.
4. Optionally, a Guzzle HandlerStack (`GuzzleHttp\HandlerStack`), which can be used to add command-level middleware to the service client.

Below is an example configured to send and receive JSON payloads:

```
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Command\CommandInterface;
use GuzzleHttp\Command\Result;
use GuzzleHttp\Command\ResultInterface;
use GuzzleHttp\Command\ServiceClient;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\UriTemplate\UriTemplate;
use GuzzleHttp\Utils;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

$client = new ServiceClient(
    new HttpClient(['base_uri' => 'https://api.example.com']),
    function (CommandInterface $command): RequestInterface {
        return new Request(
            'POST',
            UriTemplate::expand('/{command}', ['command' => $command->getName()]),
            ['Accept' => 'application/json', 'Content-Type' => 'application/json'],
            Utils::jsonEncode($command->toArray())
        );
    },
    function (
        ResponseInterface $response,
        RequestInterface $request,
        CommandInterface $command
    ): ResultInterface {
        return new Result(
            Utils::jsonDecode((string) $response->getBody(), true)
        );
    }
);
```

Executing Commands
------------------

[](#executing-commands)

Service clients create command objects using the `getCommand()` method.

```
$commandName = 'foo';
$arguments = ['baz' => 'bar'];
$command = $client->getCommand($commandName, $arguments);
```

After creating a command, you may execute the command using the `execute()`method of the client.

```
$result = $client->execute($command);
```

The result of executing a command will be an instance of an object implementing `GuzzleHttp\Command\ResultInterface`. Result objects are `ArrayAccess`-ible and contain the data parsed from HTTP response.

Service clients have magic methods that act as shortcuts to executing commands by name without having to create the `Command` object in a separate step before executing it.

```
$result = $client->foo(['baz' => 'bar']);
```

### Per-command HTTP options

[](#per-command-http-options)

`GuzzleHttp\Command\ServiceClient` reserves the `@http` command parameter for per-command Guzzle request options. When a command is executed, the service client reads `$command['@http']`, removes it from the command, transforms the remaining command data into a PSR-7 request, and passes the `@http` array to the underlying Guzzle HTTP client.

This is intended for trusted application code that needs to adjust transport behavior for a single command, such as setting a shorter timeout. Treat `@http`as a reserved control key, not as an operation parameter. Do not pass untrusted input directly into command arguments without filtering it first. If external input can include `@http`, that input may be able to influence the underlying HTTP request or transfer depending on the configured Guzzle client and handler. The `@http` value must be an array of Guzzle request options. Be especially careful with options that affect the target URI, proxy, TLS verification, headers, body, response sink, redirects, or timeouts.

Build command arguments from an allowlist of expected operation parameters, or explicitly reject reserved keys such as `@http` before creating commands:

```
if (array_key_exists('@http', $input)) {
    throw new InvalidArgumentException('"@http" is reserved.');
}

$command = $client->getCommand('foo', [
    'baz' => (string) $input['baz'],
]);
```

When setting per-command HTTP options intentionally, only expose and validate the specific options your application needs:

```
use GuzzleHttp\RequestOptions;

$command = $client->getCommand('foo', [
    'baz' => 'bar',
    '@http' => [
        RequestOptions::CONNECT_TIMEOUT => 1.0,
        RequestOptions::TIMEOUT => 2.0,
    ],
]);

$result = $client->execute($command);
```

Because `@http` is removed during execution, create a new command if you need to execute the same operation again with the same per-command HTTP options.

Asynchronous Commands
---------------------

[](#asynchronous-commands)

Commands can be executed asynchronously using `executeAsync()`. This method returns a `GuzzleHttp\Promise\PromiseInterface` that resolves to a `GuzzleHttp\Command\ResultInterface`.

```
use GuzzleHttp\Command\ResultInterface;

// Create and execute an asynchronous command.
$command = $client->getCommand('foo', ['baz' => 'bar']);
$promise = $client->executeAsync($command);

$promise->then(function (ResultInterface $result) {
    echo $result['fizz']; //> 'buzz'
})->wait();
```

Synchronous execution is equivalent to waiting on the asynchronous operation:

```
$result = $promise->wait();

echo $result['fizz']; //> 'buzz'
```

Magic methods may also be used asynchronously by appending `Async` to the operation name. For example, `fooAsync()` creates a `foo` command and executes it asynchronously:

```
$promise = $client->fooAsync(['baz' => 'bar']);
$result = $promise->wait();
```

If execution fails, the promise is rejected with a `GuzzleHttp\Command\Exception\CommandException`. When HTTP errors are enabled, 4xx and 5xx responses are represented by `CommandClientException` and `CommandServerException`, respectively, when the underlying Guzzle exception contains a response.

Concurrent Requests
-------------------

[](#concurrent-requests)

Use `executeAll()` or `executeAllAsync()` to execute multiple commands with a fixed concurrency limit. Both methods accept an array or iterator that yields `CommandInterface` objects.

`executeAll()` waits for the pool to finish and returns an array keyed like the input commands. Successful entries contain results. Failed entries contain the rejection reason, typically a `CommandException`.

```
use GuzzleHttp\Command\ResultInterface;

$commands = [
    'first' => $client->getCommand('foo', ['baz' => 'bar']),
    'second' => $client->getCommand('foo', ['baz' => 'qux']),
];

$results = $client->executeAll($commands, [
    'concurrency' => 10,
    'fulfilled' => function (ResultInterface $result, $key) {
        // Called when one command succeeds.
    },
    'rejected' => function ($reason, $key) {
        // Called when one command fails.
    },
]);
```

`executeAllAsync()` returns a promise for the command pool instead of waiting for it immediately. The same options are supported:

```
$promise = $client->executeAllAsync($commands, [
    'concurrency' => 10,
]);

$promise->wait();
```

The supported options are:

- `concurrency`: Maximum number of commands to execute at the same time. The default is `25`.
- `fulfilled`: Callable invoked as `fulfilled($result, $key)` when an individual command succeeds.
- `rejected`: Callable invoked as `rejected($reason, $key)` when an individual command fails.

Choose a concurrency value that is appropriate for the remote service and your application. Very large command lists should generally be streamed with an iterator rather than built eagerly as a large array.

Middleware: Extending the Client
--------------------------------

[](#middleware-extending-the-client)

Middleware can be added to the service client or underlying HTTP client to implement additional behavior and customize the `Command`-to-`Result` and `Request`-to-`Response` lifecycles, respectively.

Command middleware is added to the service client's handler stack and wraps commands before they are transformed into HTTP requests. HTTP middleware should be configured on the underlying Guzzle HTTP client instead.

```
use GuzzleHttp\Command\CommandInterface;
use GuzzleHttp\RequestOptions;

$client->getHandlerStack()->push(function (callable $handler) {
    return function (CommandInterface $command) use ($handler) {
        $http = $command['@http'] ?: [];
        $http[RequestOptions::TIMEOUT] = 2.0;
        $command['@http'] = $http;

        return $handler($command);
    };
});
```

Security
--------

[](#security)

If you discover a security vulnerability within this package, please send an email to . All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/command/security/policy) for more information.

License
-------

[](#license)

Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information.

For Enterprise
--------------

[](#for-enterprise)

Available as part of the Tidelift Subscription

The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-command?utm_source=packagist-guzzlehttp-command&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

###  Health Score

73

—

ExcellentBetter than 100% of packages

Maintenance98

Actively maintained with recent releases

Popularity62

Solid adoption and visibility

Community37

Small or concentrated contributor base

Maturity82

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 66.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~172 days

Recently: every ~9 days

Total

27

Last Release

9d ago

Major Versions

0.9.0 → 1.0.02016-11-24

1.5.x-dev → 2.0.x-dev2026-06-23

PHP version history (5 changes)0.2.0PHP &gt;=5.4.0

0.9.0PHP &gt;=5.5.0

1.1.0PHP &gt;=7.2.5

1.2.0PHP ^7.2.5 || ^8.0

2.0.x-devPHP ^7.4 || ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/190930?v=4)[Michael Dowling](/maintainers/mtdowling)[@mtdowling](https://github.com/mtdowling)

![](https://www.gravatar.com/avatar/401ccc5eea13c60cf807ae982af00e368e2166e2f26d8eb541dcd881a57385bc?d=identicon)[Nyholm](/maintainers/Nyholm)

![](https://www.gravatar.com/avatar/0e4e105cea62b616d4cb376b08a849b6a428f646998537de150d16a8eb537b90?d=identicon)[mark.sagikazar](/maintainers/mark.sagikazar)

![](https://www.gravatar.com/avatar/d95eb26cb8f3919bb5ca3b6d823daeabbf259663778a970349b245c580713c8e?d=identicon)[graham-campbell](/maintainers/graham-campbell)

---

Top Contributors

[![mtdowling](https://avatars.githubusercontent.com/u/190930?v=4)](https://github.com/mtdowling "mtdowling (127 commits)")[![GrahamCampbell](https://avatars.githubusercontent.com/u/2829600?v=4)](https://github.com/GrahamCampbell "GrahamCampbell (43 commits)")[![jeremeamia](https://avatars.githubusercontent.com/u/107867?v=4)](https://github.com/jeremeamia "jeremeamia (9 commits)")[![Konafets](https://avatars.githubusercontent.com/u/363363?v=4)](https://github.com/Konafets "Konafets (5 commits)")[![seiffert](https://avatars.githubusercontent.com/u/1111118?v=4)](https://github.com/seiffert "seiffert (2 commits)")[![tianyiw2013](https://avatars.githubusercontent.com/u/4644588?v=4)](https://github.com/tianyiw2013 "tianyiw2013 (1 commits)")[![bumbummen99](https://avatars.githubusercontent.com/u/4533331?v=4)](https://github.com/bumbummen99 "bumbummen99 (1 commits)")[![elyobo](https://avatars.githubusercontent.com/u/407806?v=4)](https://github.com/elyobo "elyobo (1 commits)")[![hpatoio](https://avatars.githubusercontent.com/u/249948?v=4)](https://github.com/hpatoio "hpatoio (1 commits)")[![Bolid1](https://avatars.githubusercontent.com/u/5942653?v=4)](https://github.com/Bolid1 "Bolid1 (1 commits)")

---

Tags

guzzleguzzle-servicesmiddlewarepromises

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/guzzlehttp-command/health.svg)

```
[![Health](https://phpackages.com/badges/guzzlehttp-command/health.svg)](https://phpackages.com/packages/guzzlehttp-command)
```

###  Alternatives

[aws/aws-sdk-php

AWS SDK for PHP - Use Amazon Web Services in your PHP project

6.3k543.5M2.6k](/packages/aws-aws-sdk-php)[guzzlehttp/guzzle

Guzzle is a PHP HTTP client library

23.5k1.0B35.4k](/packages/guzzlehttp-guzzle)[drupal/core-recommended

Locked core dependencies; require this project INSTEAD OF drupal/core.

6942.5M419](/packages/drupal-core-recommended)[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.5k5.9M736](/packages/sylius-sylius)[spatie/crawler

Crawl all internal links found on a website

2.8k18.5M65](/packages/spatie-crawler)[shopware/platform

The Shopware e-commerce core

3.4k1.5M3](/packages/shopware-platform)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
