个性化阅读
专注于IT技术分析

如何为Laravel 5.3创建自定义控制台命令(工匠)

点击下载

本文概述

Laravel有一个名为Artisan的命令行界面。该界面为开发人员提供了许多有用的命令, 以加快开发过程。

此外, 你可能想用自己的命令扩展artisan, 以创建和自动执行Laravel项目的独特任务。命令通常存储在app / Console / Commands目录中, 但是, 只要Composer可以加载命令, 你就可以自由选择自己的存储位置。

在本文中, 你将学习如何在Laravel 5.3中轻松为工匠创建自定义命令。

创建并注册命令

Laravel帮助你简化了一切, 它已经集成了make:console NewClassName命令来加快你的开发过程。该命令将类的名称作为第一个参数, 并且可以选择使用command选项直接指定命令的名称, 而无需修改类。

要创建名为quiz:start的新控制台命令, 请使用类名称QuizStart在控制台中执行以下命令:

php artisan make:command QuizStart --command=quiz:start

注意:如果不想使用控制台, 请在”命令结构”中复制示例类, 然后根据需要更改文件和类的名称。还要记住, 在早期版本的Laravel <5.2中, 你需要使用make:console而不是make:command。

这应该在/ app / console / commands目录中使用App \ Console \ Commands命名空间创建QuizStart类。

最后, 我们的命令未注册, 因此我们需要将其添加到$ commands数组中的/app/console/Kernel.php文件中(提供类路径和名称):

protected $commands = [
    // Commands\Inspire::class, 'App\Console\Commands\QuizStart'
];

使用php artisan cache:clear清除缓存并尝试使用先前给定的名称执行命令:

php artisan quiz:start

不出所料, 该命令什么都不做, 现在你只需要学习如何处理该命令即可。

命令结构

要自定义命令和描述的名称, 请直接在类中更改名称, 命令的所有逻辑都将存储在handle函数中。

<?php
#/App/Console/Commands/QuizStart.php
namespace App\Console\Commands;

use Illuminate\Console\Command;

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

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

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

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

列印文字

要将输出发送到控制台, 可以在以下方法之间进行选择:行, 信息, 注释, 问题和错误方法。这些方法都将使用适当的ANSI颜色作为其用途。

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $this->line("Some text");
    $this->info("Hey, watch this !");
    $this->comment("Just a comment passing by");
    $this->question("Why did you do that?");
    $this->error("Ops, that should not happen.");
}

命令输入:参数和选项

在命令中包含参数和选项

如果未设置期望功能的参数或选项, 则即使使用参数执行命令, 命令也将无法工作。

在Laravel中, 我们直接在字符串中定义参数和选项的是签名属性(命令名称)(与旧版本的Laravel不同):

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'quiz:start {user} {age} {--difficulty=} {--istest=}';

参数以简单的{argumentName}语法和选项为{–optionName =}在我们的命令中注册。所以现在我们不需要在类中创建get选项和get arguments方法。

它的语法很容易理解, 基本上所有这些都是在命令中使用参数和选项的方式(如果你需要更多详细信息, 请阅读文档):

  • 参数:quiz:start {参数}。
  • 可选参数(请注意参数名称旁边的问号):quiz:start {argument?}。
  • 具有默认值的参数:quiz:start {argument = defaultValue}。
  • 布尔选项:quiz:start –myOption。
  • 具有值的选项:quiz:start –myOption =。
  • 具有值和默认值的选项:quiz:start –myOption = 12。

检索参数和选项值

如果你的命令需要一些值才能工作(参数), 则需要访问这些值才能在命令中使用它们。要完成此任务, 可以使用arguments和option方法:

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    // Get single Parameters
    $username = $this->argument('user');
    $difficulty = $this->option('difficulty');

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

    // Stop execution and ask a question 
    $answer = $this->ask('What is your name?');

    // Ask for sensitive information
    $password = $this->secret('What is the password?');

    // Choices
    $name = $this->choice('What is your name?', ['Taylor', 'Dayle'], $default);

    // Confirmation

    if ($this->confirm('Is '.$name.' correct, do you wish to continue? [y|N]')) {
        //
    }
}

例子

以下功能将在控制台中创建一个交互式测验, 你需要回答所有这些测验。填写完测验后, 它将显示你键入的答案。

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

    if(!$difficulty){
        $difficulty = 'easy';
    }

    $this->line('Welcome '.$this->argument('user').", starting test in difficulty : ". $difficulty);

    $questions = [
        'easy' => [
            'How old are you ?', "What is the name of your mother?", 'Do you have 3 parents ?', 'Do you like Javascript?', 'Do you know what is a JS promise?'
        ], 'hard' => [
            'Why the sky is blue?', "Can a kangaroo jump higher than a house?", 'Do you think i am a bad father?', 'why the dinosaurs disappeared?', "why don't whales have gills?"
        ]
    ];

    $questionsToAsk = $questions[$difficulty];
    $answers = [];

    foreach($questionsToAsk as $question){
        $answer = $this->ask($question);
        array_push($answers, $answer);
    }

    $this->info("Thanks for do the quiz in the console, your answers : ");

    for($i = 0;$i <= (count($questionsToAsk) -1 );$i++){
        $this->line(($i + 1).') '. $answers[$i]);
    }
}
Laravel工匠测验

从控制器或路径执行命令

显然, 当我们使用ask方法时, 它不起作用, 但是对于其他方法, 你可以使用以下命令执行命令:

$exitCode = Artisan::call('quiz:start', [
    'user' => 'Carlos', '--difficulty' => 'hard'
]);

如果你需要有关工匠的更多信息, 可以在此处阅读文档。玩得开心 !

赞(0)
未经允许不得转载:srcmini » 如何为Laravel 5.3创建自定义控制台命令(工匠)

评论 抢沙发

评论前必须登录!