laravel 增加自建 artisan 命令 的简单例子

1、使用 artisan 命令生成一个command脚手架文件:aSampleCommand

php artisan make:command aSampleCommand

 

 

 

2、打开该文件\app\Console\Commands\aSampleCommand.php,编辑 

    protected $signature = 'create:user {name=lucas}';//为命令命名,使用方法: php artisan order:user amy 
    protected $description = 'a sample Command for test';//命令描述,使用 php artisan list 时可以看到

 

3、在\app\Console\Commands\aSampleCommand.php编辑该命令需要处理的业务逻辑

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $name = $this->argument('name'); //获取命令变量name
        echo "create user {$name} success";
        //
    }

4、测试使用  

F:\laravel-blog>php artisan create:user amy
create user amy success

  

注意,如果command文件保存在默认的\app\Console\Commands 目录不需要注册即可使用,如果放在其他目录则需要在  \app\Console\Kernel.php 的 $commands 变量中注册

    protected $commands = [
       Commands\CreateLogicCommand::class,
    ];

 

结束  

 

posted @ 2021-08-10 16:49  i金少  阅读(140)  评论(0编辑  收藏  举报