Laravel 5 - Creating Artisan Command for Packages

筅森魡賤 提交于 2019-12-20 11:44:08

问题


I have been following along http://laravel.com/docs/5.0/commands and able to create artisan command in Laravel 5. But, how can I create artisan command and package it to packages?


回答1:


You can and should register the package commands inside a service provider using $this->commands() in the register() method:

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);
    }
}



回答2:


In laravel 5.6 it's very easy.

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 is the serviceprovider of package. (Just need to add $this->commands() part to boot function).

<?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,
        ]);
    }
}

Now we can call the command like this

php artisan foo:method

This will echo 'foo' from command handle method. The important part is giving correct namespace of command file inside boot function of package service provider.



来源:https://stackoverflow.com/questions/28492394/laravel-5-creating-artisan-command-for-packages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!