美文网首页
laravel下command执行php脚本!

laravel下command执行php脚本!

作者: DragonersLi | 来源:发表于2018-06-09 21:35 被阅读61次

一、创建:

php artisan make:command sync#创建脚本 
php artisan command:sync #执行脚本 
php artisan command:方法 参数【--参数名=参数值】
php artisan command:sync file  #执行带参数的脚本
php artisan command:sync --file #执行带参数的脚本
ctrl + C #撤销执行

二、修改kernel.php,引入创建

image.png

三、修改sync.php

主要代码:
    protected $signature = 'command:sync {param?} {--func=}';
//command:name 改成文件名 
//{param?} 可选参数,不用指定参数名
//{--func=}  --func=参数名 ,指定参数名
public function handle(){
  //默认调用此方法
}

demo示例:


namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

set_time_limit(0); //解除PHP脚本时间30s限制
ini_set('memory_limit','128M');//修改内存值
class sync extends Command
{ 
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:sync {param?} {--func=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description: 调用示例,联系人同步:
php artisan command:sync contacts or php artisan command:sync --func=contacts ';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 入口方法
        $param = $this->argument('param'); // argument不指定参数名的情况下用 file
        $func = $this->option('func'); // option用--开头指定参数名 --func=file
        $method =  isset($param) ? $param : $func;//兼容两种传参方式调用
        //本类中是否存在传来的方法
          if(!method_exists(new self,$method)){
            echo '不存在的方法,请确认输入是否有误!';
          }else{
            self::$method();
          }

    }
    //同步
    public static function index(){
    $s = 0;//从0开始
    $e = 10; //取10条数据
        while(true){//死循环模拟分页执行代码

     if($s >=100){//满足条件跳出死循环
         exit('success');
     }  
    //执行代码
    file_put_contents('./test.log',$s.'--'.$e."\n",FILE_APPEND);
    
    $s = $s+$e; //下次分页开始
        }
   }
    //文件同步
    public static  function file(){
        echo"文件同步";

    }

    //会员同步
    public static  function file(){
        echo"会员同步";

    }
    //联系人同步
    public static function contacts(){
            echo "联系人同步";
    }

}



index执行结果:php artisan command:sync index (php artisan command:sync --func=index)
image.png image.png

相关文章

网友评论

      本文标题:laravel下command执行php脚本!

      本文链接:https://www.haomeiwen.com/subject/zseasftx.html