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).
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
composer require symfony/console
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.
touch console
Now, let's make sure that the file is executable.
chmod 755 console
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:
#!/usr/bin/env php <?php require_once __DIR__ . '/vendor/autoload.php'; use Symfony\Component\Console\Application; $app = new Application(); $app->run();
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:
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:
composer require symfony/console
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 byis as follows:
touch console
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.
chmod 755 console
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.
Let's run it:
#!/usr/bin/env php <?php require_once __DIR__ . '/vendor/autoload.php'; use Symfony\Component\Console\Application; $app = new Application(); $app->run();
We see the final result:
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.
<?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; } }
Then, register the command in the console.
<?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); } }
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
composer require symfony/console
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 FAQHow 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
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
