原文: http://zetcode.com/symfony/commands/

Symfony 控制台命令教程介绍了如何在 Symfony 中创建控制台命令。 我们将在控制台应用中创建几个命令。

Symfony

Symfony 是一组可重用的 PHP 组件和一个用于 Web 项目的 PHP 框架。 Symfony 于 2005 年发布为免费软件。Symfony 的原始作者是 Fabien Potencier。 Symfony 受到 Spring 框架的极大启发。

Symfony 控制台组件

Symfony 控制台组件使我们可以创建命令行命令。 控制台命令可用于创建 CronJob,导入,批处理作业或某些支持性任务。 Symfony 控制台命令可以在 Symfony 控制台应用或 Web 应用中使用。 在本教程中,我们将为控制台应用创建命令。

Symfony 控制台命令示例

在以下示例中,我们使用 Symfony 控制台组件创建 Symfony 控制台应用。

  1. $ mkdir commands
  2. $ cd commands

我们创建一个项目目录并找到它。

  1. $ composer require symfony/console

我们安装console包。

composer.json

  1. {
  2. "name": "Symfony command application",
  3. "description":
  4. "This application demonstrates the usage of a Symfony command in a console application",
  5. "require": {
  6. "symfony/console": "^4.2"
  7. },
  8. "autoload": {
  9. "psr-4": {
  10. "App\\": "src"
  11. }
  12. }
  13. }

我们更新composer.json文件。 我们启用App名称空间下src目录中的 PHP 类的自动加载。

  1. $ composer dump-autoload -o

创建文件后,我们需要调用composer dump-autoload -o命令,该命令将创建一个将类映射到 PHP 文件的文件。

在应用中,我们将有五个命令:

  • TimeCommand - 显示当前日期和时间
  • MessageCommand - 显示来自用户输入的消息
  • ColorCommand - 以彩色显示消息
  • BooksCommand - 在表格中显示书籍列表
  • AskNameCommand - 交互式询问用户名

这些命令在src/Command目录中创建。 社区必须扩展Symfony\Component\Console\Command并实现其configure()execute()方法。

之后,将命令与add()一起添加到Symfony\Component\Console\Application

src/Command/TimeCommand.php

  1. <?php
  2. namespace App\Command;
  3. use Symfony\Component\Console\Command\Command;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Output\OutputInterface;
  6. class TimeCommand extends Command
  7. {
  8. protected function configure()
  9. {
  10. $this->setName('time')
  11. ->setDescription('Shows current date and time')
  12. ->setHelp('This command prints the current date and time');
  13. }
  14. protected function execute(InputInterface $input, OutputInterface $output)
  15. {
  16. $now = date('c');
  17. $message = sprintf("Current date and time: %s", $now);
  18. $output->writeln($message);
  19. }
  20. }

TimeCommand显示当前日期和时间。

  1. protected function configure()
  2. {
  3. $this->setName('time')
  4. ->setDescription('Shows current date and time')
  5. ->setHelp('This command prints the current date and time');
  6. }

configure()中,我们使用setName()设置命令的名称。 名称将显示在可用命令列表中。 我们还为命令添加了描述和帮助。

  1. protected function execute(InputInterface $input, OutputInterface $output)
  2. {
  3. $now = date('c');
  4. $message = sprintf("Current date and time: %s", $now);
  5. $output->writeln($message);
  6. }

InputInterface用于从用户获取输入,OutputInterface用于显示输出。 在我们的例子中,我们使用标准 ISO 格式的date()获取当前日期和时间,并使用writeln()将其输出到控制台。

src/Command/MessageCommand.php

  1. <?php
  2. namespace App\Command;
  3. use Symfony\Component\Console\Command\Command;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Output\OutputInterface;
  6. use Symfony\Component\Console\Input\InputArgument;
  7. class MessageCommand extends Command
  8. {
  9. protected function configure()
  10. {
  11. $this->setName('msg')
  12. ->setDescription('Prints a user provided message')
  13. ->setHelp('This command prints a message provided by the user')
  14. ->addArgument('msg', InputArgument::REQUIRED, 'Pass a message');
  15. }
  16. protected function execute(InputInterface $input, OutputInterface $output)
  17. {
  18. $message = sprintf('The message is: %s', $input->getArgument('msg'));
  19. $output->writeln($message);
  20. }
  21. }

MessageCommand打印从用户的参数检索到的消息,并将其输出到控制台。

  1. $this->setName('msg')
  2. ->setDescription('Prints a user provided message')
  3. ->setHelp('This command prints a message provided by the user')
  4. ->addArgument('msg', InputArgument::REQUIRED, 'Pass a message');

该参数可以是必需的,也可以是可选的。 InputArgument::REQUIRED值使该参数成为必需参数。

  1. $message = sprintf('The message is: %s', $input->getArgument('msg'));
  2. $output->writeln($message);

我们从输入中检索带有getArgument()的参数,然后使用writeln()将该参数写入控制台。

src/Command/ColorCommand.php

  1. <?php
  2. namespace App\Command;
  3. use Symfony\Component\Console\Command\Command;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Output\OutputInterface;
  6. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  7. class ColorCommand extends Command
  8. {
  9. protected function configure()
  10. {
  11. $this->setName('colc')
  12. ->setDescription('Shows output in color')
  13. ->setHelp('This command shows output in color');
  14. }
  15. protected function execute(InputInterface $input, OutputInterface $output)
  16. {
  17. $output->writeln("<info>Today is a windy day</info>");
  18. $outputStyle = new OutputFormatterStyle('red');
  19. $output->getFormatter()->setStyle('redt', $outputStyle);
  20. $output->writeln('<redt>Tomorrow will be snowing</redt>');
  21. }
  22. }

ColorCommand以彩色输出文本。

  1. $output->writeln("<info>Today is a windy day</info>");

在这种情况下,我们使用内置的info格式样式。

  1. $outputStyle = new OutputFormatterStyle('red');
  2. $output->getFormatter()->setStyle('redt', $outputStyle);
  3. $output->writeln('<redt>Tomorrow will be snowing</redt>');

我们还可以使用OutputFormatterStyle创建自定义输出样式。 我们的redt以红色显示文字。

src/Command/BooksCommand.php

  1. <?php
  2. namespace App\Command;
  3. use Symfony\Component\Console\Helper\Table;
  4. use Symfony\Component\Console\Command\Command;
  5. use Symfony\Component\Console\Input\InputInterface;
  6. use Symfony\Component\Console\Output\OutputInterface;
  7. class BooksCommand extends Command
  8. {
  9. protected function configure()
  10. {
  11. $this->setName('books')
  12. ->setDescription('Shows books in a table')
  13. ->setHelp('This command demonstrates the usage of a table helper');
  14. }
  15. protected function execute(InputInterface $input, OutputInterface $output)
  16. {
  17. $table = new Table($output);
  18. $table->setHeaderTitle('Books')
  19. ->setHeaders(['Title', 'ISBN', 'Author', 'Publisher'])
  20. ->setRows([
  21. ['Java Language Features', '978-1-4842-3347-4', 'Kishori Sharan', 'Apress' ],
  22. ['Python Testing with pytest', '978-1-68-050-240-4', 'Brian Okken', 'The Pragmatic Programmers' ],
  23. ['Deep Learning with Python', '978-1-61729-443-3', 'Francois Chollet', 'Manning' ],
  24. ['Laravel up & Running', '978-1-491-93698-5', 'Matt Stauffer', 'O\'Reilly' ],
  25. ['Sams Teach Yourself TCP/IP', '978-0-672-33789-5', 'Joe Casad', 'SAMS' ]
  26. ]);
  27. $table->render();
  28. }
  29. }

BooksCommand使用表格助手以表格格式输出数据。

  1. $table = new Table($output);

我们创建一个Table帮助器的实例。

  1. $table->setHeaderTitle('Books')
  2. ->setHeaders(['Title', 'ISBN', 'Author', 'Publisher'])
  3. ->setRows([
  4. ['Java Language Features', '978-1-4842-3347-4', 'Kishori Sharan', 'Apress' ],
  5. ['Python Testing with pytest', '978-1-68-050-240-4', 'Brian Okken', 'The Pragmatic Programmers' ],
  6. ['Deep Learning with Python', '978-1-61729-443-3', 'Francois Chollet', 'Manning' ],
  7. ['Laravel up & Running', '978-1-491-93698-5', 'Matt Stauffer', 'O\'Reilly' ],
  8. ['Sams Teach Yourself TCP/IP', '978-0-672-33789-5', 'Joe Casad', 'SAMS' ]
  9. ]);

我们建立表。 表标题标题由setHeaderTitle()指定。 header名称由setHeaders()指定。 最后,将数据与setRows()相加。

  1. $table->render();

该表使用render()呈现。

src/Command/AskNameCommand.php

  1. <?php
  2. namespace App\Command;
  3. use Symfony\Component\Console\Command\Command;
  4. use Symfony\Component\Console\Question\Question;
  5. use Symfony\Component\Console\Input\InputInterface;
  6. use Symfony\Component\Console\Output\OutputInterface;
  7. class AskNameCommand extends Command
  8. {
  9. protected function configure()
  10. {
  11. $this->setName('ask')
  12. ->setDescription('Interactively asks name from the user')
  13. ->setHelp('This command asks a user name interactively and prints it');
  14. }
  15. protected function execute(InputInterface $input, OutputInterface $output)
  16. {
  17. $helper = $this->getHelper('question');
  18. $question = new Question("Enter your name: ", "guest");
  19. $name = $helper->ask($input, $output, $question);
  20. $message = sprintf("Hello %s!", $name);
  21. $output->writeln($message);
  22. }
  23. }

AskNameCommand使用问题助手来请求用户输入。

  1. $helper = $this->getHelper('question');

使用getHelper()创建一个问题帮助器。

  1. $question = new Question("Enter your name: ", "guest");

创建一个新的Question问题。 第二个参数是默认值。

  1. $name = $helper->ask($input, $output, $question);

问题通过ask()激活。 用户输入存储在$name变量中。

  1. $message = sprintf("Hello %s!", $name);

我们使用sprintf()从用户输入构建消息。

  1. $output->writeln($message);

最后,该消息在终端中显示为writeln()

使用Symfony\Component\Console\Application创建一个新的 Symfony 应用。

Application.php

  1. <?php
  2. require __DIR__ . '/vendor/autoload.php';
  3. use App\Command\TimeCommand;
  4. use App\Command\BooksCommand;
  5. use App\Command\ColorCommand;
  6. use App\Command\AskNameCommand;
  7. use App\Command\MessageCommand;
  8. use Symfony\Component\Console\Application;
  9. $app = new Application();
  10. $app->add(new MessageCommand());
  11. $app->add(new TimeCommand());
  12. $app->add(new AskNameCommand());
  13. $app->add(new BooksCommand());
  14. $app->add(new ColorCommand());
  15. $app->run();

我们用五个命令创建一个 Symfony 控制台应用。

  1. $app = new Application();

创建一个新的控制台应用。

  1. $app->add(new MessageCommand());
  2. $app->add(new TimeCommand());
  3. $app->add(new AskNameCommand());
  4. $app->add(new BooksCommand());
  5. $app->add(new ColorCommand());

我们向应用添加命令。

  1. $app->run();

应用从run()启动。

  1. $ php application.php list
  2. Console Tool
  3. ...
  4. Available commands:
  5. ask Interactively asks name from the user
  6. books Shows books in a table
  7. colc Shows output in color
  8. help Displays help for a command
  9. list Lists commands
  10. msg Prints a user provided message
  11. time Shows current date and time

我们可以获得命令列表。

  1. $ php application.php books
  2. +----------------------------+--------------- Books -----------------+---------------------------+
  3. | Title | ISBN | Author | Publisher |
  4. +----------------------------+--------------------+------------------+---------------------------+
  5. | Java Language Features | 978-1-4842-3347-4 | Kishori Sharan | Apress |
  6. | Python Testing with pytest | 978-1-68-050-240-4 | Brian Okken | The Pragmatic Programmers |
  7. | Deep Learning with Python | 978-1-61729-443-3 | Francois Chollet | Manning |
  8. | Laravel up & Running | 978-1-491-93698-5 | Matt Stauffer | O'Reilly |
  9. | Sams Teach Yourself TCP/IP | 978-0-672-33789-5 | Joe Casad | SAMS |
  10. +----------------------------+--------------------+------------------+---------------------------+

我们运行books命令。

  1. $ php application.php time
  2. Current date and time: 2018-12-20T23:27:16+01:00

我们运行time命令。

在本教程中,我们在 Symfony 控制台应用中创建了五个控制台命令。

  1. $ php application.php ask
  2. Enter your name: Peter
  3. Hello Peter!

我们运行ask命令。

在本教程中,我们在 Symfony 控制台应用中创建了五个控制台命令。

您可能也对以下相关教程感兴趣: Symfony 简介Symfony 验证教程Symfony Flash 消息Symfony 服务教程Symfony 表单教程PHP 教程