保姆级教程:Laravel里如何创建自己的命令行

9 篇文章 0 订阅

前提

安装好php8.2和laravel10.x,并且可以正常启用使用

什么是命令行

无论是mac, linux还是windows,都有一个命令行操作方式,然后有一个类似终端的程序来运行命令行交互。比如下面的是mac上的iTerm2

命令行的好处

命令行在开发里非常实用,主要原因就是简单,快速开发,快速使用。所以如果有一些创意要验证一下就可以方便的用命令行先实现,而且在 Laravel里其他地方也可以调用命令行,形成代码复用。

创建命令

只要一行命令就可以创建

./artisan make:command PullImageCommand

会在 app/Console/Commands 下生成一个文件 PullImageCommand.php 包括了一些最基本的内容。这个文件大概是这样

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class PullImageCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:pull-image-command';

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

    /**
     * Execute the console command.
     */
    public function handle()
    {
        //
    }
}

如果你手搓一个这样的文件也没什么区别,用laravel来生成就是为了方便一点格式

实现命令

生成一个基础文件后,主要在两个地方做修改,$signaturehandle()

class QuotePullImageByKeyword extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:pull-image {keyword}';

    /**
     * Execute the console command.
     */
    public function handle(PullImageContract $pullImageContract)
    {
        $keyword=$this->argument('keyword');
        if(empty($keyword)){
            $this->error('keyword is required');
            return;
        }
        // get image from keyword
        $image=$pullImageContract->pullImageByKeyword($keyword);
        $this->info('image: ' . $image);
    }
}
  • 'app:pull-image {keyword}' 这一段就是命令行的格式, {keyword} 代表了必填参数
  • $keyword=$this->argument('keyword'); 获得参数的内容
  • PullImageContract 参见  保姆级教程:Laravel中添加Service

运行命令

只要在目录下运行这个命令就行

./artisan app:pull-image test

就是以 test 为关键字搜索图片,然后下载第一张,最后会打印出图片url,类似

image: https://images.unsplash.com/photo-xxxxxx

内部调用命令

除了在命令行方式调用外,还可以在Laravel其他代码中调用

  • 另一个命令行中就可以这样调用
    $this->call('app:pull-image', [
        'keyword' => 'test'
    ]);
  • 在Model/Controller/Router等地方可以这样调用
    Artisan::call('app:pull-image', [
        'keyword' => 'test'
    ]);

总结

  • ./artisan make:command <command name> 创建命令
  • 修改 $signaturehandle() 来实现命令
  • ./artisan <命令格式> 来执行命令
  • $this->call 或 Artisan::call 可以用于内部执行命令
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值