Laravel 5 - 为包创建 Artisan 命令

Laravel 5 - Creating Artisan Command for Packages

我一直在关注 http://laravel.com/docs/5.0/commands 并能够在 Laravel 5 中创建 artisan 命令。但是,如何创建 artisan 命令并将其打包到包中?

您可以而且应该在 register() 方法中使用 $this->commands() 在服务提供商内部注册包命令:

namespace Vendor\Package;

class MyServiceProvider extends ServiceProvider {

    protected $commands = [
        'Vendor\Package\Commands\MyCommand',
        'Vendor\Package\Commands\FooCommand',
        'Vendor\Package\Commands\BarCommand',
    ];

    public function register(){
        $this->commands($this->commands);
    }
}

在laravel 5.6中非常简单。

class FooCommand,

<?php

namespace Vendor\Package\Commands;

use Illuminate\Console\Command;

class FooCommand extends Command {

    protected $signature = 'foo:method';

    protected $description = 'Command description';

    public function __construct() {
        parent::__construct();
    }

    public function handle() {
        echo 'foo';
    }

}

这是包的服务提供商。 (只需要将$this->commands()部分加入boot函数即可)

<?php
namespace Vendor\Package;

use Illuminate\Events\Dispatcher;
use Illuminate\Support\ServiceProvider;

class MyServiceProvider extends ServiceProvider {

    public function boot(\Illuminate\Routing\Router $router) {
        $this->commands([
            \Vendor\Package\Commands\FooCommand ::class,
        ]);
    }
}

现在我们可以这样调用命令了

php artisan foo:method

这将从命令句柄方法回显 'foo'。重要的部分是在包服务提供商的引导功能中给出正确的命令文件命名空间。