Skip to content

like sf command

Inhere edited this page Jan 15, 2019 · 2 revisions

像symfony console一样配置命令

支持像symfony console一样配置命令,严谨的设置每个参数和选项信息。

  • 选项支持设置 OPT_BOOLEAN OPT_REQUIRED OPT_OPTIONAL OPT_IS_ARRAY,以及短选项命
  • 参数支持 ARG_REQUIRED ARG_OPTIONAL ARG_IS_ARRAY
  • 设置为 REQUIRED 后,应用运行时会严格检查是否有对应的值传入
  • 如果将参数 设置为 ARRAY,那它必须是最后一个参数
<?php
namespace Inhere\Console\Examples\Command;

use Inhere\Console\Command;
use Inhere\Console\IO\Input;
use Inhere\Console\IO\Output;

/**
 * Class DemoCommand
 * @package Inhere\Console\Examples\Command
 */
class DemoCommand extends Command
{
    protected static $name = 'demo';
    protected static $description = 'this is a demo alone command. but config use configure(), like symfony console: argument define by position';

    /**
     * {@inheritDoc}
     * @throws \LogicException
     */
    protected function configure()
    {
        $this->createDefinition()
            ->setExample($this->parseCommentsVars('{script} {command} john male 43 --opt1 value1'))
            ->addArgument('name', Input::ARG_REQUIRED, 'description for the argument [name], is required')
            ->addArgument('sex', Input::ARG_OPTIONAL, 'description for the argument [sex], is optional')
            ->addArgument('age', Input::ARG_OPTIONAL, 'description for the argument [age], is optional')
            ->addOption('yes', 'y', Input::OPT_BOOLEAN, 'description for the option [yes], is boolean')
            ->addOption('opt1', null, Input::OPT_REQUIRED, 'description for the option [opt1], is required')
            ->addOption('opt2', null, Input::OPT_OPTIONAL, 'description for the option [opt2], is optional')
            ;
    }

    /**
     * description text by annotation. it is invalid when configure() is exists
     * @param  Input $input
     * @param  Output $output
     * @return int|void
     */
    public function execute($input, $output)
    {
        $output->write('hello, this in ' . __METHOD__);
        // $name = $input->getArg('name');

        $output->write(<<<EOF
this is argument and option example:
                                        the opt1's value
                                option: opt1 |
                                     |       |
php examples/app demo john male 43 --opt1 value1 -y
        |         |     |    |   |                |
     script    command  |    |   |______   option: yes, it use shortcat: y, and it is a Input::OPT_BOOLEAN, so no value.
                        |    |___       |
                 argument: name  |   argument: age
                            argument: sex
EOF
);
    }
}