krisanalfa/konsole

使用PHP的最小控制台应用程序。

安装: 18

依赖: 0

建议者: 0

安全: 0

星星: 0

关注者: 1

分支: 1

开放问题: 0

类型:项目

1.0.0 2016-02-21 07:52 UTC

This package is auto-updated.

Last update: 2024-08-29 03:18:33 UTC


README

Latest Stable Version Latest Unstable Version Total Downloads License Monthly Downloads Daily Downloads

介绍

Konsole 是基于 Laravel 控制台组件构建的最小控制台应用程序。要查看所有可用 Konsole 命令的列表,可以使用 list 命令。

php konsole list

每个命令还包含一个“帮助”屏幕,显示并描述命令的可用参数和选项。要查看帮助屏幕,只需在命令名称前加上 help

php konsole help generate

安装

可以通过 composer 命令简单地安装 Konsole。

composer create-project krisanalfa/konsole my-console-application
cd my-console-application
php konsole --version

编写命令

除了 Konsole 提供的命令外,您还可以构建自己的自定义命令来处理应用程序。您可以将自定义命令存储在 src/Konsole/Commands 目录中;然而,只要您的命令可以根据您的 composer.json 设置自动加载,您就可以自由选择自己的存储位置。

要创建一个新的命令,您可以使用 generate Konsole 命令,该命令将生成一个命令模板以帮助您开始。

php konsole generate SendEmails

上面的命令将在 src/Konsole/Commands/SendEmails.php 生成一个类。在创建命令时,可以使用 --command-C 选项来分配终端命令名称。

php konsole make:console SendEmails --command=emails:send

要在新创建的命令中添加描述,您可以使用 --description-D 选项。

php konsole make:console SendEmails --command=emails:send --description='Send email to a given user id.'

如果您想强制生成命令,您可以使用 --force-F 选项。

php konsole make:console SendEmails --command=emails:send --force

命令结构

一旦您的命令生成,您应该填写类的 signaturedescription 属性,这些属性将在显示命令时使用。

当您的命令执行时,将调用 handle 方法。您可以将任何命令逻辑放在此方法中。让我们看一下一个示例命令。

请注意,我们能够将所需的任何依赖项注入到命令的构造函数中。Laravel 服务容器将自动注入构造函数中类型提示的所有依赖项。为了提高代码的可重用性,保持您的控制台命令轻量级,并让它们将任务委派给应用程序服务是一个好习惯。

namespace Konsole\Commands;

use Konsole\Command;

class SendEmails extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = '';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
    }
}

命令I/O

定义输入期望

在编写控制台命令时,通常通过参数或选项从用户那里收集输入。Konsole 允许您通过命令的 signature 属性轻松定义您期望从用户那里获取的输入。该 signature 属性允许您使用类似路由的简洁语法在单个表达式中定义命令的名称、参数和选项。

所有用户提供的参数和选项都被括号包围。在以下示例中,命令定义了一个 必需 参数:user

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'email:send {user}';

您也可以使参数可选,并定义可选参数的默认值。

// Optional argument...
protected $signature = 'email:send {user?}'

// Optional argument with default value...
protected $signature = 'email:send {user=foo}'

选项,就像参数一样,也是用户输入的一种形式。然而,当它们在命令行上指定时,前面有双横线(--)。我们可以在签名中这样定义选项:

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'email:send {user} {--pretending}';

在这个例子中,当调用 Konsole 命令时,可以指定 --pretending 开关。如果传递了 --pretending 开关,则选项的值将是 true。否则,值将是 false

php konsole email:send 1 --pretending

您还可以通过在选项名称后缀一个 = 符号来指定该选项应由用户分配值,表示需要提供值

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'email:send {user} {--pretending=}';

在此示例中,用户可以这样传递选项值

php konsole email:send 1 --pretending=default

您还可以为选项分配默认值

protected $signature = 'email:send {user} {--pretending=default}';

在定义选项时分配快捷键,您可以在选项名称之前指定它,并使用 | 分隔符将快捷键与完整选项名称分开

protected $signature = 'email:send {user} {--P|pretending}';

如果您想定义期望数组输入的参数或选项,可以使用 * 字符

protected $signature = 'email:send {user*}';

或者

protected $signature = 'email:send {user} {--id=*}';

输入描述

您可以通过冒号将参数与描述分开来为输入参数和选项分配描述

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'email:send
                        {user : The ID of the user}
                        {--pretending= : Whether the job should be prentended}';

检索输入

当您的命令执行时,显然您需要访问您的命令接受的参数和选项的值。为此,您可以使用 argumentoption 方法

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $userId = $this->argument('user');

    //
}

如果您需要检索所有参数作为 array,请无参数调用 argument

$arguments = $this->argument();

使用 option 方法可以像检索参数一样轻松地检索选项。与 argument 方法一样,您可以在没有任何参数的情况下调用 option 以检索所有选项作为 array

// Retrieve a specific option...
$isPretending = ($this->option('pretending') !== null);

// Retrieve all options...
$options = $this->option();

如果参数或选项不存在,将返回 null

提示输入

除了显示输出外,您还可以在命令执行期间要求用户提供输入。使用 ask 方法将提示用户输入,接受他们的输入,然后将用户的输入返回到您的命令

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $name = $this->ask('What is your name?');
}

secret 方法与 ask 类似,但用户在控制台输入时看不到他们的输入。此方法在请求敏感信息(如密码)时非常有用

$password = $this->secret('What is the password?');

请求确认

如果您需要请求用户进行简单确认,您可以使用 confirm 方法。默认情况下,此方法将返回 false。但是,如果用户在提示时输入 y,则方法将返回 true

// The default answer is 'no|N'
if ($this->confirm('Do you wish to continue? [y|N]')) {
    // Do something if user answer 'yes|y'
}

给用户一个选择

可以使用 anticipate 方法提供可能的答案的自动完成。用户仍然可以选择任何答案,而不管自动完成提示

$name = $this->anticipate('What is your name?', ['Alfa', 'Fitria']);

如果您需要提供预定义的答案集给用户,您可以使用 choice 方法。用户选择答案的索引,但返回给您的是答案的值。您可以设置默认值,如果没有选择,则返回该值

$name = $this->choice('What is your name?', ['Alfa', 'Fitria'], $default);

编写输出

要向控制台发送输出,请使用 lineinfocommentquestionwarnerror 方法。这些方法中的每一个都将使用其用途的适当 ANSI 颜色。

要向用户显示信息消息,请使用 info 方法。通常,这将在控制台以绿色文本显示

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $this->info('Display this on the screen');
}

要显示警告消息,请使用 warn 方法。警告消息文本通常以橙色显示

$this->warn('Something went wrong!');

要显示错误消息,请使用 error 方法。错误消息文本通常以红色显示

$this->error('Something went wrong!');

如果您想显示纯控制台输出,请使用 line 方法。该 line 方法不接收任何独特的颜色化

$this->line('Display this on the screen');

如果您想建议用户做某事,可以使用 suggest 方法

$this->suggest('Better you pick Sven, because you have Magnus on your side.');

表格布局

table 方法可以轻松地格式化多行/多列的数据。只需将标题和行传递给该方法。宽度和高度将根据给定数据动态计算

$headers = ['Name', 'Email'];

$this->table($headers, $collection->toArray());

进度条

对于长时间运行的任务,显示进度指示器可能会有所帮助。使用输出对象,我们可以开始、前进和停止进度条。您必须在开始进度时定义步数,然后在每一步之后前进进度条

$bar = $this->output->createProgressBar(count($users));

foreach ($users as $user) {
    $this->performTask($user);

    $bar->advance();
}

$bar->finish();

要获取更多高级选项,请查看 Symfony 进度条组件文档

注册命令

您的命令执行完毕后,需要将其注册到 Konsole 中,以便可以使用。这需要在 config/app.php 文件中完成。您可以在 commands 部分添加您的命令

'commands' => [
    'Konsole\Commands\SendEmails',
    'Konsole\Commands\GenerateCommand',
],

在某些情况下,您可能希望通过 Service Provider 注册您的命令。这需要在 bootstrap/app.php 文件中完成。在此文件中,您可以通过 registerCommand 方法注册自己的命令

$konsole->registerCommand('Konsole\Commands\SendEmails');

或者,如果您想添加多个命令,可以将 registerCommand 方法的参数传递为数组

$konsole->registerCommand([
    'Konsole\Commands\FooBarBaz',
    'Konsole\Commands\SendEmails',
    'Konsole\Commands\AnotherCommand',
]);

从其他命令调用命令

有时您可能希望从现有的 Konsole 命令中调用其他命令。您可以使用 call 方法来这样做。此 call 方法接受命令名称和命令参数数组

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $this->call('email:send', [
        'user' => 1, '--pretending' => 'default'
    ]);

    //
}

如果您想要调用另一个控制台命令并抑制所有输出,可以使用 callSilent 方法。callSilent 方法与 call 方法具有相同的签名

$this->callSilent('email:send', [
    'user' => 1, '--pretending' => 'default'
]);

日志记录

Konsole 日志功能在强大的 Monolog 库之上提供了一个简单的层。默认情况下,Konsole 配置为为您的应用程序创建每日日志文件,这些文件存储在 var/log 目录中。您可以使用 $konsole->make('log') 对象将信息写入日志。Konsole 日志记录器提供了在 RFC 5424 中定义的八个日志级别:紧急警报关键错误警告通知信息调试

$konsole->log->emergency($message);
$konsole->log->alert($message);
$konsole->log->critical($message);
$konsole->log->message($message);
$konsole->log->warning($message);
$konsole->log->notice($message);
$konsole->log->info($message);
$konsole->log->debug($message);

上下文信息

您还可以将一组上下文数据传递给日志方法。这些上下文数据将与日志消息一起格式化和显示

$konsole->make('log')->info('User failed to login.', ['id' => $user->id]);

访问底层 Monolog 实例

Monolog 有许多额外的处理程序可用于日志记录。如果需要,您可以使用 Konsole 使用的底层 Monolog 实例

$monolog = $konsole->make('log');