Symfony的Console组件的简单使用。

1.进入项目路径:

cd ~/web/project/

2.安装Console组件:

composer require symfony/console @stable

3.创建自己的代码目录:

mkdir -p src/Mycmd # 创建自己的代码目录

4.注册命名空间:

编辑 composer.json 文件如下,然后在命令行输入composer dump-autoload

{
   "require": {
       "symfony/console": "@stable"
   },
   "autoload": {
       "psr-4":{
           "Mycmd\\": "src/Mycmd"
       }
   }
}
5创建要执行的命令文件:

src/Mycmd 路径下创建 TestCmd.php 文件,并写入:

<?php

namespace Mycmd;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * 
 */
class TestCmd extends Command
{
    public function __construct($msg)
    {
        $this->msg = $msg;
        parent::__construct();
    }

    protected function configure()
    {
        $this->setName('test');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln("<comment>".$this->msg."</comment>");
    }
}

6.在项目根目录下,创建Console组件的入口文件 console 并写入:

#!/usr/bin/env php
<?php

require __DIR__.'/vendor/autoload.php';

use Mycmd\TestCmd;
use Symfony\Component\Console\Application;

$application = new Application();
$application->add(new TestCmd("hello console"));
$application->run();

使用组件:

php console.php test
转自:https://segmentfault.com/a/1190000005084734

猜你喜欢

转载自blog.csdn.net/u011323949/article/details/79310752