[扩展推荐] Laravel 命令行任务 Micro

本周我写了一个小扩展,你可能会发现你的 Laravel Artisan 命令很有趣。软件包称为「Laravel Console Task」,它允许你执行有输出结果的任务。

0

控制台的结果

Github 链接: https://github.com/nunomaduro/laravel-cons...

你可以使用 composer 在你的 Laravel 项目中安装这个扩展:

composer require nunomaduro/laravel-console-task

要求 & 使用:

  • PHP ≥ 7.0.0
  • Laravel ≥ v5.5.26
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class LaravelInstallCommand extends Command
{
    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $this->task('Downloading Laravel', function () {
            return Laravel::install();
        });
    }
}

实现这个扩展非常简单:Laravel v5.5.26 使类 Illuminate \ Console \ Command 可以使用宏,所以本质上我们可以通过服务提供商提供任务方法:

<?php
declare(strict_types=1);
/**
 * This file is part of Laravel Console Task.
 *
 * (c) Nuno Maduro <enunomaduro@gmail.com>
 *
 *  For the full copyright and license information, please view the LICENSE
 *  file that was distributed with this source code.
 */
namespace NunoMaduro\LaravelConsoleTask;
use Illuminate\Console\Command;
use Illuminate\Support\ServiceProvider;
/**
 * This is an Laravel Console Task Service Provider implementation.
 *
 * @author Nuno Maduro <enunomaduro@gmail.com>
 */
class LaravelConsoleTaskServiceProvider extends ServiceProvider
{
    /**
     * {@inheritdoc}
     */
    public function boot()
    {
        /*
         * Performs the given task, outputs and
         * returns the result.
         *
         * @param  string $title
         * @param  callable $task
         *
         * @return bool With the result of the task.
         */
        Command::macro(
            'task',
            function (string $title, callable $task) {
                return tap($task(), function ($result) use ($title) {
                    $this->output->writeln(
                        "$title: ".($result ? '<info>✔</info>' : '<error>failed</error>')
                    );
                });
            }
        );
    }
}

如果你喜欢命令行应用,查看社区项目Laravel Zero,默认包含这个扩展。

你是否发现这个扩展很有趣??

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://medium.com/@nunomaduro/laravel-c...

译文地址:https://learnku.com/laravel/t/18538

本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!