Home >Backend Development >PHP Tutorial >Re-Introducing Symfony Console - CLI PHP for the Uninitiated!

Re-Introducing Symfony Console - CLI PHP for the Uninitiated!

Christopher Nolan
Christopher NolanOriginal
2025-02-10 14:06:15555browse

Re-Introducing Symfony Console - CLI PHP for the Uninitiated!

Core points

  • Symfony Console is a standalone package that provides a simple framework for creating command line tools, which is useful for repetitive tasks such as data migration, importing, or creating cron jobs.
  • To create a new command, the file needs to be executable. This can be done by creating a console file in the project root directory, ensuring the file is executable, and defining the console application.
  • You can use Symfony's CommandTester class to test commands, which provides special input and output classes to test commands without the command line.
  • Symfony Console is installed using Composer (the dependency management tool in PHP). It provides a simple API to create command-line commands and supports color displays, progress bars, tables and other interactive features of the output.

This article was updated on May 24, 2017 and provides a more comprehensive introduction to this important modern tool.


"Console component simplifies the process of creating a beautiful and testable command-line interface."

This is the welcome message we see when we visit the Symfony Console Component Tools page.

As software developers, we often need to use command line tools. These tools are useful when we need to perform some kind of repetitive tasks (such as migrating data, executing imports, or creating cron jobs).

Re-Introducing Symfony Console - CLI PHP for the Uninitiated!

The Symfony Console component tool provides us with a simple framework to create our own command line tools.

Unlike many components in Symfony, this is a standalone package that is used by Laravel's Artisan and many other famous PHP packages.

To learn about the alternatives to Symfony Console, see our comparison article: Battle of PHP Console!

Installation

<code class="language-bash">composer require symfony/console</code>

Important information about Composer is included here.

Create a new command

To create a new command, we need to make sure our file is executable. To do this, let's create a console file in the project root directory. This file will serve as our command manager.

<code class="language-bash">touch console</code>

Now, let's make sure that the file is executable.

<code class="language-bash">chmod 755 console</code>

Then, let's make sure that there is shebang at the beginning of our file. shebang is a sequence of characters (thumb mark followed by exclamation mark) that appears at the beginning of the script. When shebang exists, exec() will change to the executable file specified after shebang is run. In our example, it will run as a PHP script.

After

, let's define our console application. The first iteration of our command manager will look like this:

<code class="language-php">#!/usr/bin/env php

<?php require_once __DIR__ . '/vendor/autoload.php';

use Symfony\Component\Console\Application;

$app = new Application();
$app->run();</code>

Let's take a closer look. First, we automatically load all dependencies and then import the Application package from the Console component. After that, we create a new instance of Application and run it.

If we use ./console to execute the script, we should get the following help message:

Re-Introducing Symfony Console - CLI PHP for the Uninitiated!

This is because we haven't registered any commands yet, we just built their basic framework.

Let's create our script and register it in our newly created command manager.

For this specific example, we will implement two simple commands: one for hashing strings and the other for confirming that the hash belongs to the given string.

We will place the /src folder of our Hash.php class, with the following content:

<code class="language-bash">composer require symfony/console</code>

It's time to create our commands. Let's create a new PHP file called HashCommand.php.

This class will extend Symfony's Command class and implement configure and execute methods. These methods are crucial to our commands because they tell the commands how they look and behave.

The command completed by

is as follows:

<code class="language-bash">touch console</code>

In the configuration section, the setName method is the way we call the command, setDescription is the description of the command, and addArgument is the statement we declare that the command will accept a parameter named Password, and it is required.

In the execute section, we access the parameters through the getArgument function and then hash them using our Hash class. Finally, we use OutputInterface's writeeln method to print the result to the screen.

If we run our command like this, we will see nothing happening. This is because we are still missing a very important step. We still need to register our commands in the console.

<code class="language-bash">chmod 755 console</code>

After registering the command in the console, let's run it.

If we run the ./console command again, we can see that we have now registered a new command.

Re-Introducing Symfony Console - CLI PHP for the Uninitiated!

Let's run it:

<code class="language-php">#!/usr/bin/env php

<?php require_once __DIR__ . '/vendor/autoload.php';

use Symfony\Component\Console\Application;

$app = new Application();
$app->run();</code>

We see the final result:

Re-Introducing Symfony Console - CLI PHP for the Uninitiated!

Hash is the result of applying the PHP hash() method to a Sitepoint string.

For the hash confirmation function we will use the same method, but we will have two parameters instead of one. One will be the string that needs to be confirmed, and the other will be the hash value that we want to verify.

We will create a new command file, right next to the HashCommand file. Let's call it ConfirmCommand.

<code class="language-php"><?php
namespace Hash;

class Hash {

    /**
     * 接收一个字符串密码并对其进行哈希处理。
     *
     * @param string $password
     * @return string $hash
     */
    public static function hash($password) {
        return password_hash($password, PASSWORD_DEFAULT);
    }

    /**
     * 验证哈希是否与给定的密码相对应
     *
     * @param string $password
     * @param string $hash
     * @return boolean 如果哈希是从密码生成的
     */
    public static function checkHash($string, $hash) {
        if (password_verify($string, $hash)) {
            return true;
        }
        return false;
    }

}</code>

Then, register the command in the console.

<code class="language-php"><?php
namespace Hash;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;

use Hash\Hash;

class HashCommand extends Command {

    protected function configure() {
        $this->setName("Hash:Hash")
                ->setDescription("使用Bcrypt对给定字符串进行哈希处理。")
                ->addArgument('Password', InputArgument::REQUIRED, '你想要哈希什么?');
    }

    protected function execute(InputInterface $input, OutputInterface $output) {

        $hash = new Hash();
        $input = $input->getArgument('Password');

        $result = $hash->hash($input);

        $output->writeln('你的密码哈希值:' . $result);

    }

}</code>

Test

In terms of testing, Symfony provides us with some convenient tools. The most useful one is the CommandTester class, because it provides special input and output classes to test our commands without the command line.

Let's use the CommandTester class to implement a test for our Hash:Hash command.

First, let's create a /src folder at the same level as ours. /tests

Then, let's create our test class in it and name it HashCommandTest.php:

<code class="language-bash">composer require symfony/console</code>
We first load our commands using the Application class. Then, we instantiate a new CommandTester. Using CommandTester, we can configure how we want to call our commands. The last step is to use the getDisplay() method to compare the execution result with the result we expect.

The

getDisplay() method saves the result of our command execution, just like we see on the command line.

Conclusion

We just created two different commands using the Symfony Console component. We also see a good way to test these commands. I suggest you look at the various options and features of the components and give us some feedback on your experiment in the comments section below.

Do you want to see more advanced tutorials on Symfony Console on SitePoint? Please tell us!

All the code we wrote in this article can be found on Github.

Symfony Console FAQ

How to install Symfony Console?

Symfony Console is a component of the Symfony framework that can be installed using Composer (the dependency management tool in PHP). To install Symfony Console, you need to run the following command in the terminal:

. This command will download and install the Symfony Console component into your project. composer require symfony/console

What are the main functions of Symfony Console?

Symfony Console provides a simple API to create command-line commands. These commands can be used for cron jobs, migrations, imports, or any other task type that can be run through the command line. It also supports color displays, progress bars, tables and other interactive features of the output.

How to create a new command in Symfony Console?

To create a new command, you need to create a new class that extends the SymfonyComponentConsoleCommand class. In this class, you define the name, description, parameters, and options of the command in the configure method. The execute method contains the logic of the command.

How to run commands in Symfony Console?

To run the command, you need to use the

script followed by the name of the command. For example, if you have a command called bin/console, you can run it with the following command: app:my-command. bin/console app:my-command

How to use Symfony Console for database migration?

Symfony Console can be used in conjunction with Doctrine (the database abstraction layer in Symfony) to manage database migrations. You can create a new command that executes the necessary SQL queries to migrate your database.

How to handle command parameters and options in Symfony Console?

Command parameters and options can be defined in the configure method of the command class. You can use the getArgument and getOption methods to retrieve the values ​​of these parameters and options in the execute method.

How to display output in Symfony Console?

Symfony Console provides several ways to display output. You can use the writeeln method to display a line of text, use the write method to display text (no line breaks at the end), and use the table method to display table.

How to handle errors in Symfony Console?

Errors can be handled by throwing exceptions. Symfony Console will catch these exceptions and display an error message. You can also use the exit method to stop the execution of the command and return the exit code.

How to test commands in Symfony Console?

Symfony Console provides a CommandTester class that can be used to test commands. You can use this class to execute commands with specific parameters and options and assert the output and exit code.

How to use Symfony Console in Symfony project?

In the Symfony project, you can use the bin/console script to run commands. You can also create your own commands by creating a new class extending the SymfonyComponentConsoleCommand class in the src/Command directory.

The above is the detailed content of Re-Introducing Symfony Console - CLI PHP for the Uninitiated!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn