laravel自定义artisan命令

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaanghao/article/details/86493887
//命令生成文件 app/Console/Commands/TopicMakeExcerptCommand.php
php artisan make:console TopicMakeExcerptCommand --command=topics:excerpt
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class TopicMakeExcerptCommand extends Command
{
    /**
     * 1. 这里是命令行调用的名字, 如这里的: `topics:excerpt`, 
     * 命令行调用的时候就是 `php artisan topics:excerpt`
     *
     * @var string
     */
    protected $signature = 'topics:excerpt';

    /**
     * 2. 这里填写命令行的描述, 当执行 `php artisan` 时
     *   可以看得见.
     *
     * @var string
     */
    protected $description = '这里修改为命令行的描述';

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

    /**
     * 3. 这里是放要执行的代码, 如在我这个例子里面,
     *   生成摘要, 并保持.
     *
     * @return mixed
     */
    public function handle()
    {
        $topics = Topic::all();
        $transfer_count = 0;

        foreach ($topics as $topic) {
          if (empty($topic->excerpt))
          {
              $topic->excerpt = Topic::makeExcerpt($topic->body);
              $topic->save();
              $transfer_count++;
          }
        }
        $this->info("Transfer old data count: " . $transfer_count);
        $this->info("It's Done, have a good day.");
    }
}
//在 app/Console/Kernel.php 文件里面, 添加以下
 protected $commands = [
        \App\Console\Commands\TopicMakeExcerptCommand::class,
    ];
//命令行调用
   php artisan topics:excerpt 

猜你喜欢

转载自blog.csdn.net/zhaanghao/article/details/86493887