A guide to a proper PHP Console Application

Googling this topic, I could only find official documentation on Symfony’s Console Component and some tutorials on quick building, but i’d like to write about making a real scalable console application that you could use in an actual production project. I’ll explain the reasons we do each of the things.

I like to write decoupled, reusable and as raw as possible code, so we’ll try to aim on that direction. Also, we’ll take advantage of all of the new features of PHP 7. Remember that this means that you’ll require a version higher than 7.1.

Basically, we will only use a dependency container and Symfony’s Console Component and put them together. Should be fairly easy and simple. Personally, I like Zend’s Service Manager, but you can use any dependency container you like. Try to pick a PSR-11 compiling one.

Let’s start by initialising a composer definition and requiring the service manager:

composer init --require zendframework/zend-servicemanager && composer install

We must also require Symfony’s console component:

composer require symfony/console

Let’s create a console command. Nothing fancy, just a standard Symfony Command:

src/App/Command/MyCommand.php

Remember to autoload your code in your composer.json:

“autoload”: {
“psr-4”: {
“App\\”: “src/App/”
}
}

Next step would be registering this command as a service. We want this application to be able to scale, that’s why it’s important to keep a clean dependency injection control.

For simplicity’s sake, I will use anonymous functions for the factories, but in a real project, I’d use proper factory classes.

config/services.php

I recommend to keep all of your commands as services, even if they won’t have dependencies. Also, we’ll create a config file that returns all of the commands for the application.

The only thing left would be to create the front controller. We just need to instantiate a new Console and register all of our commands, that we’ll load from our confir file and pull from our container ;)

We’ll use an extension-less file:

config/commands.php
application

That’s it!

You should be able to run php application my:command and see My awesome command! printed in the console.

Some people would extend Symfony’s Application class, but I think it’s not necessary since that class is already meant to be extended for this use case.

You can create all the commands and services you need. Just add the commands you create to the config file. This intended to be scalable and PHP 7 standard compiling.

I created a Github repository where you can see a fully-running example.

I’d be glad to answer any questions you have.

Hope this is useful to someone! Cheers!