Skip to content

v3 add command

Inhere edited this page May 28, 2022 · 1 revision

添加独立命令

public function command(string $name, $handler = null, $option = null)
  • $handler 一个可调用的 callable 或者 继承类 Inhere\Console\Command
  • $option string|array 命令的选项信息,传入字符串则作为描述

使用 callable

callable 可以是 闭包函数,具名函数,可回调的对象

如下所示,使用闭包可以快速的添加一个简单的命令

$app->command('demo', function (Input $in, Output $out) {
    $cmd = $in->getCommand();

    $out->info('hello, this is a test command: ' . $cmd);
}, 'this is message for the command');

$app->command('demo2', function (Input $in, Output $out) {
    $cmd = $in->getCommand();

    $out->info('hello, this is a test command: ' . $cmd);
}, [ // 使用数组可以配置更多信息
	'aliases' => ['alias-name'], // 配置别名
	'description' => 'this is message for the command',
]);

独立命令 - 继承Command

通过继承 Inhere\Console\Command 添加独立命令

独立命令 - 只有一个命令可执行,跟 symfony/console 的 command 一样

use Inhere\Console\Command;

/**
 * Class TestCommand
 * @package app\console\commands
 */
class TestCommand extends Command
{
    // 命令名称
    protected static $name = 'test';
    // 命令描述
    protected static $description = 'this is a test independent command';

    /**
     * @usage usage message
     * @arguments 
     *  arg     some message ...
     *  
     * @options 
     *  -o, --opt     some message ...
     *  
     * @param  Inhere\Console\IO\Input $input
     * @param  Inhere\Console\IO\Output $output
     * @return int
     */
    public function execute($input, $output)
    {
        $output->write('hello, this in ' . __METHOD__);
    }
}

注释中的 @usage @arguments @options @example 在使用 帮助命令时,会被解析并显示出来

执行命令

$ php example/app test
hello, this in Inhere\Console\Examples\Command\TestCommand::execute

命令帮助

$ php example/app test -h

Clone this wiki locally
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy