加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-14 20:03:00 所属栏目:大数据 来源:网络整理
导读:前言 本文主要跟大家介绍的是关于laravel通过创建自定义artisan make命令来新建类文件的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。 我们在laravel开发时经常用到 artisan make:controller 等命令来新建Controller、Model

前言

本文主要跟大家介绍的是关于laravel通过创建自定义artisan make命令来新建类文件的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

我们在laravel开发时经常用到artisan make:controller等命令来新建Controller、Model、Job、Event等类文件。 在Laravel5.2中artisan make命令支持创建如下文件:

不过,有时候默认的并不能够满足我们的需求, 比方我们在项目中使用的Respository模式来进一步封装了Model文件,就需要经常创建Repository类文件了,时间长了就会想能不能通过artisan make:repository命令自动创建类文件而不是都每次手动创建。

系统自带的artisan make命令对应的PHP程序放在IlluminateFoundationConsole目录下,我们参照IlluminateFoundationConsoleProviderMakeCommand类来定义自己的artisan make:repository命令。

一、创建命令类

在appConsoleCommands文件夹下创建RepositoryMakeCommand.php文件,具体程序如下:

use IlluminateConsoleGeneratorCommand;

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';
    }
    }

二、创建命令类对应的模版文件

在appConsoleCommandsstubs下创建模版文件 .stub文件是make命令生成的类文件的模版,用来定义要生成的类文件的通用部分创建repository.stub模版文件:

use AppRepositoriesBaseRepository;

class DummyClass extends BaseRepository
{

/**

  • Specify Model class name
  • @return string
    */
    public function model()
    {
    //set model name in here,this is necessary!
    }
    }

三、注册命令类

将RepositoryMakeCommand添加到AppConsoleKernel.php中

测试命令

好了, 现在就可以通过make:repository命令来创建repository类文件了

php artisan make:repository SubDirectory/TestRepository

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程之家的支持。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读