繁体   English   中英

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 中这很容易。

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() 部分添加到引导功能中)。

<?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 工匠 foo: 方法

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM