How-to › Ship a CLI or REPL

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.

Audience
API consumer
Level
intermediate
Topic
Build a CLI over an API
Languages
PHP
Verified

Your PHP tool for the orders API is one script with a switch on $argv[1]. Every case builds its own Guzzle request, query string, and status check, so a change to the base URL lands in four places. --help lists nothing, and the script that calls tool orders list breaks the day the argument order moves.

What you get

You will end up with a bin/console whose orders:list and orders:get commands are one class each, over a generated PHP SDK you can swap without touching them. This is for you if you consume an API from PHP and want a CLI your team and its scripts can rely on.

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

ApproachWhen it fitsWhat it costs youWhen to pick something else
Fern PHP SDKThe vendor generates its PHP SDK with Fern and publishes it to PackagistGeneration needs a Fern login, a guest session, or Docker, and its CLI generator writes RustYou generate the SDK yourself, offline
GuzzleOne or two calls, and no SDK existsEvery command repeats the URL, query, decoding, and status handling the SDK holds onceA third command needs the same request code
Laravel ZeroYou want a PHAR or a standalone binary, and Laravel Prompts for inputA customized Laravel underneath, which is a large framework for two commandsA plain Symfony Console tool covers what you ship
minicliYou want no dependencies, or orders list with a space as gh doesFewer input helpers than Symfony Console, and no shell completion mentioned in its READMEYou want completion and per-option validation built in
sdkgen PHP targetThe API owner generates with sdkgen, and you want paging read from the responseGlobal classes, one named plain Order, and a package its README says is not on PackagistYour codebase forbids global classes, or the vendor ships another SDK
Swagger Codegen PHP clientYou generate the client yourself from OpenAPI 3.0 and like Guzzle underneathIn 3.0.85, a model for a referenced enum that PHP cannot parse until you patch itThe 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.

(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, from lib/.

    "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] names the command. The part before the colon is the namespace bin/console list groups it under. configure() declares one option or argument per API parameter: the limit and cursor query parameters become options, and --all follows next_cursor.

#[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.

    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,
        ];
    }
ORDERDESK_STANDIN=1 php bin/console list
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
ORDERDESK_STANDIN=1 php bin/console orders:list --cursor cur_0003
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 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.

{
  "invokerPackage": "Orderdesk\\Swagger",
  "packagePath": "orderdesk-swagger",
  "composerVendorName": "orderdesk",
  "composerProjectName": "orderdesk-swagger"
}
ORDERDESK_STANDIN=1 ORDERDESK_SDK=swagger php bin/console orders:list --all
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 for all generated code, which is the value your PSR-4 key must match. The current sdk-config.yml PHP page lists naming.clientName, propertyAccess, and generateClientInterfaces, and its shared reference has package.namespace, “the namespace or package prefix for generated code”. Fern’s own CLI generator 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.

php test.php
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

php pitfall.php
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 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.

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.

Footnotes

  1. Composer’s schema documentation 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. ↩︎ Back to text

  2. The PHP generator’s option list 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. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.