Laravel5.5+ 新建(自定义) artisan 命令

本文介绍在Laravel框架中如何创建自定义Artisan命令,包括生成命令类、设置命令签名、描述及主方法等内容,助您轻松扩展框架功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在项目开发过程中,为了方便,我们可能需要自定义一个属于自己的 artisan 命令执行特殊的任务.

那么如果在 Laravel 中如何新建一个属于自己的 artisan 命令呢?

1. 生成命令类

php artisan 命令可以列出所有可用的 artisan 命令,其中有一个命令是 artisan make command 

 make command 命令是用来生成自定义命令类的.现在我们用这个命令来生成一个自己的命令类

php artisan make:command DemoCommandTest --command=demo:test:nwei

DemoCommandTest 是新建的命令类, demo:test:nwei 是我们自定义的命令

我们修改我们的命令类如下:

<?php

namespace App\Console\Commands;

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

class DemoCommandTest extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'demo:test:nwei';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '这个一个新的命令类,自定义的哦';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $this->info("开始执行....");

        Log::info("逻辑代码在这里....");

        $this->info("执行结束...");
    }
}

description 是命令描述.可以修改.

handle() 是主方法,所有的逻辑都在 handle() 方法中.

2. 执行 artisan

执行 php artisan 可以看到刚才新建的命令,如下:

执行我们的自定义命令 

laravel.log 文件中多了一条记录

这就是如何在 laravel 中自定义自己的 artisan 命令.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值