[扩展推荐] Laravel 命令行任务 Micro
本周我写了一个小扩展,你可能会发现你的 Laravel Artisan 命令很有趣。软件包称为「Laravel Console Task」,它允许你执行有输出结果的任务。
控制台的结果
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 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
推荐文章: