Laravel 5 - 为包创建 Artisan 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28492394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5 - Creating Artisan Command for Packages
提问by user1995781
I have been following along http://laravel.com/docs/5.0/commandsand able to create artisan command in Laravel 5. But, how can I create artisan command and package it to packages?
我一直在关注http://laravel.com/docs/5.0/commands并且能够在 Laravel 5 中创建 artisan 命令。但是,我如何创建 artisan 命令并将其打包到包中?
回答by lukasgeiter
You can and should register the package commands inside a service provider using $this->commands()
in the register()
method:
您可以并且应该使用$this->commands()
以下register()
方法在服务提供者中注册包命令:
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);
}
}
回答by vimuth
In laravel 5.6 it's very easy.
在 Laravel 5.6 中这很容易。
class FooCommand,
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 serviceproviderof package. (Just need to add $this->commands() part to boot function).
这是包的服务提供者。(只需要将 $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,
]);
}
}
Now we can call the command like this
现在我们可以像这样调用命令
php artisan foo:method
php 工匠 foo: 方法
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.
这将从命令句柄方法中回显 'foo'。重要的部分是在包服务提供者的引导函数中给出正确的命令文件命名空间。