# How to build a Symfony Console CLI over a generated PHP SDK

> Write one Symfony Console command class per verb, such as orders:list, over a generated PHP SDK passed in through an interface, not Guzzle calls in each command.

Source: https://voxgig.com/howto/symfony-console-cli-over-a-php-sdk

- Audience: api-consumer
- Level: intermediate
- Languages: php
- Verified: 2026-11-20
- Published: 2026-11-20

## Short answer

With Symfony Console, write one command class per verb, name it with #[AsCommand(name: 'orders:list')] so the colon groups commands by resource, and declare an InputOption or InputArgument for each API parameter. Pass the command a client built from a generated PHP SDK, behind a two-method interface, rather than raw Guzzle calls. Map the SDK's namespace in composer.json, and call orders:list in scripts, never orders list.

---
## You will need

PHP 8.2 or later with Composer, and a generated PHP SDK for the API. Verified 2026-11-20 against
PHP 8.3.6, Composer 2.8.12, Symfony Console 7.4.23, Guzzle 7.16.3, Swagger Codegen 3.0.85, and
@voxgig/sdkgen 4.44.3. The document, `api.json`, has `listOrders` with `limit` and `cursor` and
`getOrder` with an `orderId` path parameter. `ORDERDESK_STANDIN=1` answers every request from
`src/StandIn.php` in memory, so no command on this page reaches a network.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Fern PHP SDK](https://buildwithfern.com/learn/sdks/legacy/generators/php/configuration) | The vendor generates its PHP SDK with Fern and publishes it to Packagist | Generation needs a Fern login, a guest session, or Docker, and its CLI generator writes Rust | You generate the SDK yourself, offline |
| [Guzzle](https://docs.guzzlephp.org/en/stable/handlers-and-middleware.html) | One or two calls, and no SDK exists | Every command repeats the URL, query, decoding, and status handling the SDK holds once | A third command needs the same request code |
| [Laravel Zero](https://laravel-zero.com/docs/introduction) | You want a PHAR or a standalone binary, and Laravel Prompts for input | A customized Laravel underneath, which is a large framework for two commands | A plain Symfony Console tool covers what you ship |
| [minicli](https://github.com/minicli/minicli) | You want no dependencies, or `orders list` with a space as gh does | Fewer input helpers than Symfony Console, and no shell completion mentioned in its README | You want completion and per-option validation built in |
| [sdkgen PHP target](https://github.com/voxgig/sdkgen/blob/main/docs/how-to/add-a-target.md) | The API owner generates with sdkgen, and you want paging read from the response | Global classes, one named plain `Order`, and a package its README says is not on Packagist | Your codebase forbids global classes, or the vendor ships another SDK |
| [Swagger Codegen PHP client](https://swagger.io/docs/open-source-tools/swagger-codegen/codegen-v3/generators-configuration/) | You generate the client yourself from OpenAPI 3.0 and like Guzzle underneath | In 3.0.85, a model for a referenced enum that PHP cannot parse until you patch it | The document uses `$ref` enums and you cannot post-process the output |

Voxgig maintains sdkgen. It is one of six options here, not the recommendation.

Symfony Console is the frame in every row, and the choice is what sits under it. A generated SDK
keeps request building, decoding, and errors in one place, at the price of a generator step and a
namespace to wire. Guzzle alone is lighter until the second command copies the first. minicli and
Laravel Zero replace the frame itself: one removes every dependency, the other adds a framework.

## Generate the SDK and map it in Composer

`generate.sh` ran both generators once and committed their PHP under `generated/`. The sdkgen part
adds the `php` target and the `paging` feature.

```bash title="generate.sh"
(cd "$WORK" && npx --yes @voxgig/create-sdkgen@0.31.9 orderdesk --def api.json \
  --target php --feature paging)
(cd "$WORK/orderdesk-sdk/.sdk" && npm run generate)
```

The two SDKs load differently, and `composer.json` has to say so. sdkgen's own classes, such as
`OrderdeskSDK` and a class named plain `Order`, sit in the global namespace, and only its bundled
`Voxgig\Struct` utility declares one. Its own `composer.json` loads them by `files` and `classmap`. Swagger Codegen's sit under the `invokerPackage` namespace, loaded by
[PSR-4](https://www.php-fig.org/psr/psr-4/), from `lib/`.

```json title="composer.json"
    "autoload": {
        "psr-4": {
            "Orderdesk\\Cli\\": "src/",
            "Orderdesk\\Swagger\\": "generated/swagger/lib/"
        },
        "files": ["generated/sdkgen/orderdesk_sdk.php"],
        "classmap": ["generated/sdkgen/"]
    },
```

The PSR-4 key has to match the namespace in the generated files, with the trailing `\\`, and the
path has to end at `lib/`.[^1] Both mistakes surface as a class that is not found at the first
command, and a section below shows each.

## Write one command class per verb

[`#[AsCommand]`](https://symfony.com/doc/current/console.html) names the command. The part before
the colon is the namespace `bin/console list` groups it under. `configure()` declares one
[option or argument](https://symfony.com/doc/current/console/input.html) per API parameter: the
`limit` and `cursor` query parameters become options, and `--all` follows `next_cursor`.

```php title="src/Command/ListOrdersCommand.php"
#[AsCommand(name: 'orders:list', description: 'List orders, newest first, one page at a time')]
final class ListOrdersCommand extends Command
{
    public function __construct(private Orders $orders)
    {
        parent::__construct();
    }

    protected function configure(): void
    {
        // From the listOrders parameters in api.json: limit (1 to 100) and cursor.
        $this
            ->addOption('limit', 'l', InputOption::VALUE_REQUIRED, 'Orders per page, 1 to 100', '3')
            ->addOption('cursor', null, InputOption::VALUE_REQUIRED, 'The next_cursor of the previous page')
            ->addOption('all', null, InputOption::VALUE_NONE, 'Follow next_cursor until the last page');
    }
```

`orders:get` takes `orderId` as a required `InputArgument` and refuses `""`, `.`, and `..` before
any request, since each would address another path. The constructor takes `Orders`, a two-method
interface, so the command holds no URL, no header, and no JSON.

## Inject the sdkgen SDK behind the interface

`SdkgenOrders` adapts the SDK. Its `paging` feature reads the cursor from the response into
`$client->_paging['last']`, and because PHP copies arrays, the next call gets the cursor back by
hand.

```php title="src/SdkgenOrders.php"
    public function page(int $limit, ?string $cursor): array
    {
        $ctrl = $cursor === null ? [] : ['paging' => ['cursor' => $cursor]];
        $entities = $this->call(fn () => $this->client->Order()->list(['limit' => $limit], $ctrl));
        $paging = $this->client->_paging['last'] ?? [];
        return [
            'items' => array_map(fn ($entity) => self::order($entity->data_get()), $entities),
            'next' => ($paging['hasMore'] ?? false) ? ($paging['cursor'] ?? null) : null,
        ];
    }
```

```bash
ORDERDESK_STANDIN=1 php bin/console list
```

```text output
Available commands:
  completion   Dump the shell completion script
  help         Display help for a command
  list         List commands
 orders
  orders:get   Load one order
  orders:list  List orders, newest first, one page at a time
```

```bash
ORDERDESK_STANDIN=1 php bin/console orders:list --cursor cur_0003
```

```text output
ord_104  refunded    99.00
ord_105  paid        12.75
ord_106  shipped     64.00
next: --cursor cur_0006
```

The `orders` heading comes from the colon. The last line hands the next cursor back in the form
the option takes, so a person can page by hand and a script can follow it.

## Wire the same commands to Swagger Codegen and Fern

Swagger Codegen reads generator options from a JSON file passed with `-c`, as its
[configuration page](https://swagger.io/docs/open-source-tools/swagger-codegen/codegen-v3/generators-configuration/)
describes, and the PHP generator takes the namespace from `invokerPackage`.[^2] The generated `DefaultApi` takes a Guzzle client, which is where the stand-in plugs
in, and `SwaggerOrders` maps its `OrderPage` model to the same two methods.

```json title="swagger-config.json"
{
  "invokerPackage": "Orderdesk\\Swagger",
  "packagePath": "orderdesk-swagger",
  "composerVendorName": "orderdesk",
  "composerProjectName": "orderdesk-swagger"
}
```

```bash
ORDERDESK_STANDIN=1 ORDERDESK_SDK=swagger php bin/console orders:list --all
```

```text output
ord_101  paid        42.50
ord_102  shipped     18.00
ord_103  pending      7.25
ord_104  refunded    99.00
ord_105  paid        12.75
ord_106  shipped     64.00
ord_107  paid        30.00
```

The commands did not change. Only `Console::orders()` picked the other adapter.

Fern generates PHP SDKs on its service or in Docker, so it was not run here. Its legacy
`generators.yml` configuration has a [`namespace`
option](https://buildwithfern.com/learn/sdks/legacy/generators/php/configuration) for all generated
code, which is the value your PSR-4 key must match. The current `sdk-config.yml` [PHP
page](https://buildwithfern.com/learn/sdks/current/generators/php/configuration) lists
`naming.clientName`, `propertyAccess`, and `generateClientInterfaces`, and its shared
[reference](https://buildwithfern.com/learn/sdks/current/reference/sdk-config) has
`package.namespace`, "the namespace or package prefix for generated code". Fern's own [CLI
generator](https://buildwithfern.com/learn/cli-generator/get-started/quickstart) writes a Rust
project, so a PHP CLI over a Fern SDK is the same adapter and command classes as here.

## Check it worked

`test.php` runs every command through Symfony's `ApplicationTester` against both SDKs.

```bash
php test.php
```

```text output
ok 1 - list groups both commands under the orders namespace
ok 2 - both SDKs print the same first page, next page, and --all
ok 3 - --all prints all seven orders from three requests
ok 4 - orders:get prints one order and exits 1 on a 404
ok 5 - an id is sent as one escaped path segment, and dot segments are refused
ok 6 - --limit outside 1 to 100 is refused before any request
ok 7 - the space form runs no command and exits 1
ok 8 - an abbreviation that a later command makes ambiguous stops working
ok 9 - --all stops when the API repeats a cursor
ok 10 - the PSR-4 prefix must name the generated namespace and lib/
ok 11 - sdkgen classes are global, Order among them, and only Struct has a namespace
ok 12 - the enum model parses only after the commas are added
12 tests, 12 passed, 0 failed
```

The second test compares the two SDKs' output byte for byte, and the third counts the stand-in's
requests, so a `--all` that stopped after one page fails it.

## When it goes wrong

```bash
php pitfall.php
```

```text output
1. the space form is not the command
   orders list -> exit 1, 0 requests, "Available commands for the "orders" namespace:"
   orders:list -> exit 0, 1 requests, "ord_101  paid        42.50"

2. a path segment that is not an id
   sdkgen  orders:get a/b -> exit 1, sent GET /v1/orders/a%2Fb
   swagger orders:get a/b -> exit 1, sent GET /v1/orders/a%2Fb
   orders:get .. -> exit 1, 0 requests, "".." is not an order id"

3. a PSR-4 prefix that misses the generated namespace
   Orderdesk\Swagger\ => generated/swagger/lib/ DefaultApi found
   Orderdesk\Swagger\ => generated/swagger/     DefaultApi not found
   Swagger\Client\ => generated/swagger/lib/    DefaultApi not found
   Orderdesk\Swagger => generated/swagger/lib/  DefaultApi refused: A non-empty PSR-4 prefix must end with a namespace separator.

4. the enum model Swagger Codegen wrote
   generated/swagger-as-generated/OrderStatus.php   exit 255: PHP Parse error:  syntax error, unexpected identifier "self", expecting "]" on line 57
   generated/swagger/lib/Model/OrderStatus.php      exit 0: No syntax errors detected in generated/swagger/lib/Model/OrderStatus.php
```

A script calls `orders list` and gets help text with exit 1. Symfony reads `orders` as the command
name, finds a namespace, and lists it. The colon cannot become a space as it does in `gh`, so
scripts must spell `orders:list` in full. Abbreviations such as `o:l` work until a second command
starts with the same letters, which the eighth test shows.

Both SDKs escape `a/b` into one segment, so the CLI only has to refuse the dot segments.

The first command fails with a class that is not found. A PSR-4 path that stops short of `lib/`, or
the generator's default `Swagger\Client` namespace, finds nothing. Match the key to the generated
files.

The CLI dies with a parse error in `OrderStatus.php`. The [enum
template](https://github.com/swagger-api/swagger-codegen-generators/blob/master/src/main/resources/handlebars/php/model_enum.mustache)
writes a comma only under `{{#hasMore}}`, and 3.0.85 wrote none for the four values of this
document's `OrderStatus`. `generate.sh`
adds the commas with one `sed` after each run.

## When not to do this

Do not wrap an SDK for one call. A command with a single Guzzle request is shorter than an
interface, an adapter, and a generator step, and the SDK pays off from the second command.

Do not adopt sdkgen to get a PHP CLI over someone else's API. Its SDK classes sit in the global
namespace, the package is not on Packagist, and you would own a generator for a vendor's document.
Swagger Codegen is the better choice when you generate a client yourself and want PSR-4
namespaces, provided you patch referenced enums. Fern is the better choice when the vendor already
publishes a Fern PHP SDK, because then there is nothing to generate.

Do not build on Laravel Zero for two commands unless you need its PHAR or binary build. Pick
minicli instead of Symfony Console when scripts must call `orders list` with a space, since its
command namespaces read the second word as the command.

## Related how-tos

- [Map API parameters to CLI arguments and flags](/howto/map-api-parameters-to-cli-flags-and-arguments)

- [Derive a noun-verb command tree from an OpenAPI document](/howto/derive-a-command-tree-from-operation-ids)

- [Design an exception hierarchy for a PHP API client](/howto/exception-hierarchy-for-a-php-api-client)

- [Generate your first SDK with sdkgen](/howto/first-sdk-with-sdkgen)

- [Choose Restish, a generated CLI, or a hand-written one](/howto/choose-restish-generated-or-hand-written-cli)

## Last verified

Verified 2026-11-20 against PHP 8.3.6, Composer 2.8.12, Node 22.23.5, Symfony Console 7.4.23,
Guzzle 7.16.3, @voxgig/create-sdkgen 0.31.9, @voxgig/sdkgen 4.44.3, and Swagger Codegen 3.0.85.
Every output block is what the command preceding it printed. Both generators ran once, in
`generate.sh`, and their PHP is committed under `generated/`. Every request went to the in-memory
stand-in. Fern was not run. Its options come from its documentation.

[^1]: Composer's [schema documentation](https://getcomposer.org/doc/04-schema.md#psr-4) gives the
reason for the trailing separator in one example: without it, a prefix `Foo` would match classes in
the `FooBar` namespace. Composer's class loader enforces the rule at registration, so the prefix
without it is refused before any class is looked up.

[^2]: The PHP generator's [option
list](https://github.com/swagger-api/swagger-codegen-generators/blob/master/src/main/java/io/swagger/codegen/v3/generators/php/PhpClientCodegen.java)
still describes `composerVendorName` with an important note dated 2016/03: the option will be
deprecated and replaced by `gitUserId` in the next swagger-codegen release. The 3.0.85 release
printed the same note in `config-help`, and the option still set the package name in this run.