Laravel 执行php脚本

557 阅读1分钟

前言

在框架中编写脚本要远比自己单独写脚本要方便很多,因为你可以随便调用框架的各种功能。

创建脚本文件

php artisan make:command KillGoodsCommand

注册command

在命令集文件app\console\Commands\Kernel.php文件中的commands数组中新增(没有则手写commands数组中新增(没有则手写commands数组)

image.png

修改脚本参数

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'KillGoods';

image.png

执行命令

//脚本名称是你修改过的$signature,如$signature=killGoods,则执行KillGoods

php artisan KillGoods

代码

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class KillGoodsCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'KillGoods';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '秒杀商品同步redis...';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        echo '同步开始...';echo PHP_EOL;
        for ($i = 1; $i <= 5; $i++) {
            //逻辑处理开始
            //...
            //逻辑处理结束
            echo '同步第' . $i . '条数据';
            echo PHP_EOL;
        }
        echo '同步结束...';
    }
}

效果图:

image.png