那时候刚好下着雨,柏油路面湿冷冷的,还闪烁着青、黄、红颜色的灯火。



一个简单的小例子来说明Command


一个简单的小例子来说明Command

Symfony的Command工具其实是一个非常好用,非常强大的具,方便咱们在命令行操作实现一些东西。

关于版本

这里要注意的是Symfony2.x 与Syfmony3.x有些差异。

Symfony3.x 最外层多了几个目录,如var/, bin/, tests/等,有些东西它挪到外面来了,刚开始有些不习惯,慢慢就好了

所以我们的命令都是使用 php bin/console

实现

以下的就是一个简单的实现,并没有什么技术含量,我也才刚学习,请各们大神们勿喷,谢谢啦!

安装symfony及创建项目

安装

$ sudo curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony
$ sudo chmod a+x /usr/local/bin/symfony

创建项目

$ symfony new me-dudulu-proxy

开始codeing

使用phpstorm打开项目开始编码。

如果把Symfony的Command单独拿出来讲,应该能讲很多

我在src/AppBundle 目录创建一个Command/目录,这个目录是专门为命令行操作的而存在的,也就是当你使用php app/consolephp bin/console 命令时它上面所显示的那一些命令。

$ php bin/console
Symfony version 3.1.1 - app/dev/debug

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -e, --env=ENV         The Environment name. [default: "dev"]
      --no-debug        Switches off debug mode.
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  help                                    Displays help for a command
  list                                    Lists commands
 app
  app:crawl-wechat                        抓取微信文章
  app:proxy                               通过代理请求
  app:telnet                              验证代理ip是否可用
 assets
  assets:install                          Installs bundles web assets under a public web directory
 cache
  cache:clear                             Clears the cache
  cache:warmup                            Warms up an empty cache
 config
  config:dump-reference                   Dumps the default configuration for an extension
 debug
  debug:config                            Dumps the current configuration for an extension
  debug:container                         Displays current services for an application
  debug:event-dispatcher                  Displays configured listeners for an application
  debug:router                            Displays current routes for an application
  debug:swiftmailer                       Displays current mailers for an application
  debug:translation                       Displays translation messages information
  debug:twig                              Shows a list of twig functions, filters, globals and tests
 doctrine
  doctrine:cache:clear-collection-region  Clear a second-level cache collection region.
  doctrine:cache:clear-entity-region      Clear a second-level cache entity region.
  doctrine:cache:clear-metadata           Clears all metadata cache for an entity manager
  doctrine:cache:clear-query              Clears all query cache for an entity manager
  doctrine:cache:clear-query-region       Clear a second-level cache query region.
  doctrine:cache:clear-result             Clears result cache for an entity manager
  doctrine:database:create                Creates the configured database
  doctrine:database:drop                  Drops the configured database
  doctrine:ensure-production-settings     Verify that Doctrine is properly configured for a production environment.
  doctrine:generate:crud                  Generates a CRUD based on a Doctrine entity
  doctrine:generate:entities              Generates entity classes and method stubs from your mapping information
  doctrine:generate:entity                Generates a new Doctrine entity inside a bundle
  doctrine:generate:form                  Generates a form type class based on a Doctrine entity
  doctrine:mapping:convert                Convert mapping information between supported formats.
  doctrine:mapping:import                 Imports mapping information from an existing database
  doctrine:mapping:info
  doctrine:query:dql                      Executes arbitrary DQL directly from the command line.
  doctrine:query:sql                      Executes arbitrary SQL directly from the command line.
  doctrine:schema:create                  Executes (or dumps) the SQL needed to generate the database schema
  doctrine:schema:drop                    Executes (or dumps) the SQL needed to drop the current database schema
  doctrine:schema:update                  Executes (or dumps) the SQL needed to update the database schema to match the current mapping metadata.
  doctrine:schema:validate                Validate the mapping files.
 generate
  generate:bundle                         Generates a bundle
  generate:command                        Generates a console command
  generate:controller                     Generates a controller
  generate:doctrine:crud                  Generates a CRUD based on a Doctrine entity
  generate:doctrine:entities              Generates entity classes and method stubs from your mapping information
  generate:doctrine:entity                Generates a new Doctrine entity inside a bundle
  generate:doctrine:form                  Generates a form type class based on a Doctrine entity
 lint
  lint:twig                               Lints a template and outputs encountered errors
  lint:yaml                               Lints a file and outputs encountered errors
 orm
  orm:convert:mapping                     Convert mapping information between supported formats.
 router
  router:match                            Helps debug routes by simulating a path info match
 security
  security:check                          Checks security issues in your project dependencies
  security:encode-password                Encodes a password.
 server
  server:run                              Runs PHP built-in web server
  server:start                            Starts PHP built-in web server in the background
  server:status                           Outputs the status of the built-in web server for the given address
  server:stop                             Stops PHP's built-in web server that was started with the server:start command
 swiftmailer
  swiftmailer:debug                       Displays current mailers for an application
  swiftmailer:email:send                  Send simple email message
  swiftmailer:spool:send                  Sends emails from the spool
 translation
  translation:update                      Updates the translation file

由上面可以看到,我上面已经多了三个选项目:

app
  app:crawl-wechat                        抓取微信文章
  app:proxy                               通过代理请求
  app:telnet                              验证代理ip是否可用

这三个命令选项目分别会方法我的 src/AppBundle/Command目录的三个文件,每个文件都对应了不同的功能。

下面我先简单说明一下Command操作

我理解的是,当你敲下php bin/console命令的时候,程序会去找到Command/目录下所有继承了ContainerAwareCommand /的所有类,并且当它实例代,并且注入一些需要的工具。

可以简单做一个实验:

先在src/AppBundle/Command/目录,创建一个ProxyCommad.php文件:

namespace AppBundle\Command;

use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;


/**
 * Class ProxyCommand
 * @package AppBundle\Command
 */
class ProxyCommand extends ContainerAwareCommand
{
    /**
     * @var ObjectManager
     */
    private $em;

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('app:proxy')
            ->setDescription('通过代理请求')
            ->setHelp(<<<HELP
这个 <info>%command.name%</info> 命令暂不做其他参数及功能目前就这一个功能:

  <info>php %command.full_name%</info>

HELP
            );
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return void
     */
    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        $this->em = $this->getContainer()->get('doctrine')->getManager();
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return void
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {

        $output->writeln("Hello World!");
    }

}

这里我们需要写三个方法:

configure

这个方法是这个命令的一些配制、说明或配制一些参数啥的。

这里不需要Options所我我只配制了名称,描述及说明。如果需要参数的话,可以在下面加addOptions(),如:

    
    use Symfony\Component\Console\Input\InputOption;

        $this
            ->setName('app:crawl-wechat')
            ->setDescription('抓取微信文章')
            ->setHelp(<<<HELP
这个 <info>%command.name%</info> 命令暂不做其他参数及功能目前就这一个功能:

  <info>php %command.full_name%</info>

HELP
            )
            ->addOption('crawl-category', null, InputOption::VALUE_NONE, '抓取微信分类');

InputOution 这个类里面有四个参数:

const VALUE_NONE = 1;  // 不接收参数
const VALUE_REQUIRED = 2; // 接收附加参数
const VALUE_OPTIONAL = 4; // 不知道,没试过
const VALUE_IS_ARRAY = 8; // 不知道没试过

因为我暂不需要其他参数,所以我就设置为none了。

配好上面这些东西后你可以试试: php bin/console命令,如果没错的话,它应该会多了下面这一项:

app
  app:proxy                               通过代理请求

执行命令: php bin/console app:proxy --help

$ php bin/console app:proxy --help
Usage:
  app:proxy

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -e, --env=ENV         The Environment name. [default: "dev"]
      --no-debug        Switches off debug mode.
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Help:
 这个 app:proxy 命令暂不做其他参数及功能目前就这一个功能:

   php bin/console app:proxy

如果设置了选项(Options)的话应该会显示如下:

$ php bin/console app:crawl-wechat --help
Usage:
  app:crawl-wechat [options]

Options:
      --crawl-category  抓取微信分类
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -e, --env=ENV         The Environment name. [default: "dev"]
      --no-debug        Switches off debug mode.
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Help:
 这个 app:crawl-wechat 命令暂不做其他参数及功能目前就这一个功能:

   php bin/console app:crawl-wechat

initialize

这个方法是为了初始化一些东西,比如这里我们需要用到DoctrineORM 也就是需要用到数据库,所以我们把doctrine给初始化进来了。

execute

execute就是最终我们要执行的方法体了,它注入的两个参数InputInterface $inputOutputInterface $output从字上面也能知道它是啥意思,输入的参数及输出的参数。

然后你执行一下php bin/console app:proxy看它会不会输出"Hello World";

命令行输出的色彩方案

这个其实官网已经写得很清楚了,我英文也不好,就不翻译啦,知道意思就行。

官方文档: How to Style a Console Command

这里就来个简单的:

$output->writeln(array(
            '<info>Lorem Ipsum Dolor Sit Amet</>',
            '<info>==========================</>',
            '',
        ));

好像这样写也可以:

$this->output->writeln('<fg=green,bg=yellow>balabalabala</>');
  • fg 字体颜色
  • bg 背景颜色

更多关于Command

  • 听说它能调用Controller?
  • 听说它它能模拟Form请求?
  • 听说它能模拟登录?
  • 听说它可以定义Services

那只能看我没有没心情写下一篇关于Command的文章了


 标签 , TAG , 啦啦