hiroto-k/console-wrapper

symfony/console 的包装类

1.2.0 2018-12-07 05:19 UTC

This package is auto-updated.

Last update: 2024-08-29 04:48:45 UTC


README

Build Status PHP from Packagist Maintainability License

symfony/console 的包装类

安装

composer require hiroto-k/console-wrapper:^1.0

文档

示例

示例命令类

<?php

namespace ExampleApp\Commands;

use HirotoK\ConsoleWrapper\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

/**
 * Command class of "greeting" command.
 */
class GreetingCommand extends Command
{
    /**
     * Definition the command name.
     *
     * @var string
     */
    protected $name = 'greeting';

    /**
     * Definition the command description.
     *
     * @var string
     */
    protected $description = 'Example greeting command with console-wrapper';

    /**
     * Setup the command class.
     */
    protected function setup()
    {
        // Setup class configure.
        // This method is called before the "configure" method.
    }

    /**
     * Execute the command.
     */
    protected function handle()
    {
        $greet = $this->option('hi') ? 'Hi, ' : 'Hello, ';

        $name = $this->argument('first-name');

        if ($this->hasArgument('family-name')) {
            $name .= ' '.$this->argument('family-name');
        }

        $this->writeln($greet.$name);
    }

    /**
     * Definition the command arguments.
     *
     * @see \Symfony\Component\Console\Command\Command::addArgument
     *
     * @return array
     */
    protected function commandArguments()
    {
        return [
            // [$name, $mode = null, $description = '', $default = null]
            ['first-name', InputArgument::REQUIRED, 'Your first name (required)'],
            ['family-name', InputArgument::OPTIONAL, 'Your family name (optional)'],
        ];
    }

    /**
     * Definition the command options.
     *
     * @see \Symfony\Component\Console\Command\Command::addOption
     *
     * @return array
     */
    protected function commandOptions()
    {
        return [
            // [$name, $shortcut = null, $mode = null, $description = '', $default = null]
            ['hi', null, InputOption::VALUE_NONE, 'Use "Hi".'],
        ];
    }
}

示例应用程序类

<?php

namespace ExampleApp;

use HirotoK\ConsoleWrapper\Application as WrapperApplication;
use Symfony\Component\Console\Input\InputOption;

/**
 * Customize application class.
 */
class Application extends WrapperApplication
{
    /**
     * Definition the global command options.
     *
     * @return array
     */
    protected function globalOptions()
    {
        return [
            // [$name, $shortcut = null, $mode = null, $description = '', $default = null]
            ['debug', null, InputOption::VALUE_NONE, 'Enable debug mode.'],
            ['config', 'c', InputOption::VALUE_REQUIRED, 'Set path of config file.', 'path/to/default'],
        ];
    }
}

示例执行文件

<?php

use ExampleApp\Application;
use ExampleApp\Commands\GreetingCommand;

$application = new Application();

// Add command class.
$application->add(new GreetingCommand());

// Start the application.
$application->run();

使用

参数

定义参数,使用 Command::commandArguments() 方法。

返回的数组将传递给 Command::addArgument() 方法。有关 Command::addArgument() 方法的参数,请参阅文档。

/**
 * Definition the command arguments.
 *
 * @return array
 */
protected function commandArguments()
{
    return [
        // [$name, $mode = null, $description = '', $default = null]
        ['user-id', InputArgument::REQUIRED, 'User name (required)'],
        ['task', InputArgument::OPTIONAL, 'Task name (optional)', 'default'],
    ];
}

要访问参数,请使用 Command::argument() 方法。

如果需要所有参数,请使用 Command::arguments() 方法。

要检查参数是否存在,请使用 Command::hasArgument() 方法。

protected function handle()
{
    // Get argument value.
    $userId = $this->argument('user-id');

    // Get all arguments.
    $allArguments = $this->arguments();

    // Checks whether a argument exists.
    $hasTaskArgument = $this->hasArgument('task');
}

选项

定义选项,使用 Command::commandOptions() 方法。

返回的数组将传递给 Command::addOption() 方法。有关 Command::addOption() 方法的参数,请参阅文档。

/**
 * Definition the command options.
 *
 * @return array
 */
protected function commandOptions()
{
    return [
        // [$name, $shortcut = null, $mode = null, $description = '', $default = null]
        ['name', null, InputOption::VALUE_REQUIRED, 'User name.', 'default name'],
        ['force', null, InputOption::VALUE_NONE, 'Force execute.'],
    ];
}

要访问选项,请使用 Command::option() 方法。

如果需要所有选项,请使用 Command::options() 方法。

要检查选项是否存在,请使用 Command::hasOption() 方法。

protected function handle()
{
    // Get option value.
    $name = $this->option('name');

    // Get all options.
    $allOptions = $this->options();

    // Checks whether a option exists.
    $hasForceOption = $this->hasOption('force');
}

全局选项

console-wrapper 可以轻松设置全局选项。

<?php

namespace ExampleApp;

use HirotoK\ConsoleWrapper\Application as WrapperApplication;
use Symfony\Component\Console\Input\InputOption;

class Application extends WrapperApplication
{
    /**
     * Definition the global command options.
     *
     * @return array
     */
    protected function globalOptions()
    {
        return [
            // [$name, $shortcut = null, $mode = null, $description = '', $default = null]
            ['debug', null, InputOption::VALUE_NONE, 'Enable debug mode.'],
            ['config', 'c', InputOption::VALUE_REQUIRED, 'Set path of config file.', 'path/to/default'],
        ];
    }
}

输出

console-wrapper 提供了一些输出方法。

protected function handle()
{
    // Display normal message.
    $this->writeln('message');
    $this->writeln([
        'multi',
        'line',
        'message',
    ]);

    // Display message with styles.
    $this->info('info style');
    $this->comment('comment style');
    $this->question('question style');
    $this->error('error style');
}

通过 PSR-4 自动添加命令

如果项目使用 PSR-4,则可以通过 Application::loadByPsr4() 方法自动加载所有命令。

/**
 * Auto add commands by PSR-4.
 * 
 * loadByPsr4(string $nameSpacePrefix, string $targetDir)
 */
$application->loadByPsr4("\ExampleApp\Commands", realpath(__DIR__.'/src/Commands'));

日志记录器

console-wrapper 可以轻松使用日志记录器。

在执行文件中设置日志记录器实例。日志记录器类必须实现 \Psr\Log\LoggerInterface 接口。

/**
 * Set logger instance to application and command class.
 */
$application->setLogger($logger);

在命令类中,使用 logger() 方法并使用日志记录器。

protected function handle()
{
    $this->logger()->debug('Debug message');
    $this->logger()->error('Error message');
}

默认日志记录器

如果未在应用程序中设置日志记录器实例,则默认使用 \Psr\Log\NullLogger 类。

\Psr\Log\NullLogger

protected function handle()
{
    // Output Psr\Log\NullLogger
    $this->writeln(get_class($this->logger()));
}

覆盖默认日志记录器

如果要覆盖默认日志记录器,请覆盖 Application::createDefaultLogger() 方法。返回的实例必须实现 \Psr\Log\LoggerInterface 接口。

// Use monolog in default logger

use HirotoK\ConsoleWrapper\Application as WrapperApplication;
use Monolog\Logger;

class Application extends WrapperApplication
{
    /**
     * Override default logger instance.
     * Return instance must be implement the \Psr\Log\LoggerInterface
     * 
     * @return \Monolog\Logger
     */
    protected function createDefaultLogger()
    {
        return new Logger();
    }
}

在 Command::setup 中使用日志记录器

如果在 Command::setup() 方法中使用日志记录器,必须在添加命令之前设置日志记录器实例。

// Register logger instance
$application->setLogger($logger);

// Add commands
$application->add(new GreetingCommand());
$application->loadByPsr4("\ExampleApp\Commands", realpath(__DIR__.'/src/Commands'));

助手和工具

确认问题

简单的确认。默认返回 true

protected function handle()
{
    if ($this->confirm('continue ? (y/n) ')) {
        // If enter y
    }
}

设置默认值

protected function handle()
{
    if ($this->confirm('continue ? (y/n) ', false)) {
        // If enter y
    }
}

调用其他命令

在命令类中调用其他命令。

protected function handle()
{
    // Call the "other-command-name" command
    $this->callCommand('other-command-name');
}

带参数

protected function handle()
{
    // Call the "other-command-name" command, with name parameter
    $this->callCommand('other-command-name', ['name' => 'example']);
}

渲染表格

protected function handle()
{
    // Only creates Table class instance.
    $table = $this->createTable();

    // Sets headers and rows
    $headers = ['name', 'location'];
    $rows = [
        ['Hoge', 'jp'],
        ['Foo', 'us'],
    ];
    $table = $this->createTable($headers, $rows)

    // Render table
    $table->render();
}
+------+----------+
| name | location |
+------+----------+
| Hoge | jp       |
| Foo  | us       |
+------+----------+

自定义表格,请参阅 \Symfony\Component\Console\Helper\Table 类。

// Set the column width.
$this
    ->createTable($headers, $rows)
    ->setColumnWidth(0, 10)
    ->render();

进度条

protected function handle()
{
    $progressBar = $this->createProgressBar(100);

    $progressBar->start();

    $i = 0;
    while ($i++ < 100) {
        $progressBar->advance();
    }

    $progressBar->finish();
}

自定义进度条,请参阅 \Symfony\Component\Console\Helper\ProgressBar 类。

获取助手实例

protected function handle()
{
    // Get the question helper instance
    $this->getQuestionHelper();

    // Get the process helper instance.
    $this->getProcessHelper();
}

许可证

MIT 许可证