Laravel用户自定义命令行简明教程

在laravel中命令行被称作Artisan类,你可以很轻松地使用自带的脚手架创建一个命令行文件。 我们使用欢迎新用户这样的一个假设需求做示例:

php artisan make:command Cloud --command=cloud:sync

这样就会在目录 app/Console/Commands/ 下创建一个 Cloud.php 文件。 我们来看一下这个文件长啥样。首先是头部的命名空间,和类引用:

namespace App\Console\Commands;
use Illuminate\Console\Command;

然后是类的内容:

class Cloud extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cloud:sync';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        return 0;
    }
}

为了演示,我们把注释都给去掉了。其中 $signarute 就是命令行中 --command 所声明的形式。 属性 $description 是命令的描述。

我们的业务逻辑,在 handle() 方法内实现就可以了。

要让这个命令行可以调用,需要手动注册,在 app/Console/Kernel.php 文件的添加如下内容:

protected function commands()
{
    $this->load(__DIR__.'/Commands');

    require base_path('routes/console.php');
}

这样就可以在应用根目录下,打开命令行,输入以下命令:

php artisan cloud:sync 

因为没有任何逻辑代码,执行会顺利结束,且没有任何提示信息。 现在我们给 handle 方法内添加一些业务逻辑代码:

echo '命令行执行';
php artisan cloud:sync

控制台输出内容

发表回复

电子邮件地址不会被公开。必填项已用 * 标注