Re-Introducing Symfony Console – CLI PHP for the Uninitiated!
“The console component eases the creation of beautiful and testable command line interfaces.”
This is how we are welcomed when we visit the Symfony Console component tool page.
As software developers, we often feel the need to resort to command line tools. These kinds of tools are helpful when we need to do a sort of recurring task like migrating data, performing imports, or creating cron jobs.
The Symfony Console component tool offers provides us with a simple framework to create our own command line tools.
Unlike many components in Symfony, this is a stand alone package and is used by the likes of Laravel‘s Artisan and many other famous PHP packages.
To read up on alternatives to Symfony Console, see our comparison post: PHP Console Wars!
composer require symfony/console
Essential information about Composer here.
Creating a new command
To create a new command, we need to make sure our file will be executable. In order to do that, let’s create a
console file in the root of our project. This file will be our command manager.
Now, let’s make sure the file is executable.
chmod 755 console
Then, let’s make sure our file has the shebang at the beginning. The shebang is a character sequence (a number sign followed by an exclamation mark) that appears at the beginning of a script. When the shebang is present,
exec() will instead run the executable specified after the shebang. In our case, it will run as a PHP script.
After this, let’s define our console application. The first iteration of our command manager will look like this:
#!/usr/bin/env php <?php require_once __DIR__ . '/vendor/autoload.php'; use SymfonyComponentConsoleApplication; $app = new Application(); $app->run();
Let’s take a closer look at things. First, we are autoloading all our dependencies, then importing the
Application package from the Console component. After that, we are creating a new instance of the Application and running it.
Continue reading %Re-Introducing Symfony Console – CLI PHP for the Uninitiated!%