laravel通过创建自定义artisan make命令来新建类文件详解

本文详细介绍如何在Laravel框架中自定义make命令,包括创建RepositoryMakeCommand命令类,定义命令模版,以及如何在Kernel.php中注册自定义命令。通过实例演示,如创建repository类,展示自定义make命令的强大功能。

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

 make
  make:auth            Scaffold basic login and registration views and routes
  make:command         Create a new Artisan command
  make:controller      Create a new controller class
  make:event           Create a new event class
  make:job             Create a new job class
  make:listener        Create a new event listener class
  make:mail            Create a new email class
  make:middleware      Create a new middleware class
  make:migration       Create a new migration file
  make:model           Create a new Eloquent model class
  make:notification    Create a new notification class
  make:policy          Create a new policy class
  make:provider        Create a new service provider class
  make:request         Create a new form request class
  make:seeder          Create a new seeder class
  make:test            Create a new test class

当以上make命令不能满足我需求时,请往下看

Console目录

Console目录包含应用所有自定义的Artisan命令,这些命令类可以使用make:command命令生成。该目录下还有console核心类,在这里可以注册自定义的Artisan命令以及定义调度任务。

创建命令类

1,在app\Console\Commands文件夹下创建RepositoryMakeCommand.php文件,具体程序如下:
namespace App\Console\Commands;
 
use Illuminate\Console\GeneratorCommand;
 
class RepositoryMakeCommand extends GeneratorCommand
{
 /**
  * The console command name.
  *
  * @var string
  */
 protected $name = 'make:repository';
 
 /**
  * The console command description.
  *
  * @var string
  */
 protected $description = 'Create a new repository class';
 
 /**
  * The type of class being generated.
  *
  * @var string
  */
 protected $type = 'Repository';
 
 /**
  * Get the stub file for the generator.
  *
  * @return string
  */
 protected function getStub()
 {
  return __DIR__.'/stubs/repository.stub';
 }
 
 /**
  * Get the default namespace for the class.
  *
  * @param string $rootNamespace
  * @return string
  */
 protected function getDefaultNamespace($rootNamespace)
 {
  return $rootNamespace.'\Repositories';
 }
}

注意:
1,在app\Console\Commands\stubs下创建模版文件 .stub文件是make命令生成的类文件的模版,用来定义要生成的类文件的通用部分创建repository.stub模版文件:

2, 创建命令类对应的模版文件repository.stub
namespace DummyNamespace;
 
use App\Repositories\BaseRepository;
 
class DummyClass extends BaseRepository
{
  
 /**
  * Specify Model class name
  * 
  * @return string
  */
 public function model()
 {
  //set model name in here, this is necessary!
 }
}
3,注册命令类

将RepositoryMakeCommand添加到App\Console\Kernel.php中

protected $commands = [
 Commands\RepositoryMakeCommand::class
];

测试命令

php artisan make:repository TestRepository
 
php artisan make:repository SubDirectory/TestRepository

原文链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值