Laravel怎样自定义command命令浅析

2023-06-06,

这篇文章给大家分享的是有关Laravel怎样自定义command命令浅析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

前言

用过Laravel的都知道,Laravel通过php artisan make:controller可以生成控制器,同样的夜可以用命令生成中间介和模型,那怎么自定义生成文件呢?

下面话不多说了,来一起看看详细的介绍吧

自定义方法如下:

1.创建command类

<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

class ServiceMakeCommand extends GeneratorCommand
{
 /**
  * The console command name.
  *
  * @var string
  */
 protected $name = 'make:service';

 /**
  * The console command description.
  *
  * @var string
  */
 protected $description = 'Create a new service class';

 /**
  * The type of class being generated.
  *
  * @var string
  */
 protected $type = 'Services';

 /**
  * Get the stub file for the generator.
  *
  * @return string
  */
 protected function getStub()
 {
  return __DIR__.'/stubs/service.stub';
 }

 /**
  * Get the default namespace for the class.
  *
  * @param string $rootNamespace
  * @return string
  */
 protected function getDefaultNamespace($rootNamespace)
 {
  return $rootNamespace."\Services";
 }
}

2.在Commands/stubs文件下创建自定义模板文件

<?php

namespace DummyNamespace;

class DummyClass 
{
 public function __construct()
 {

 }
}

创建了一个只有构造函数的类,具体模板可以自己定义

运行测试

php artisan make:service Web/TestService

这个时候Services文件下的Web目录下会生成TestService文件,Web目录不存在时会自动创建

感谢各位的阅读!关于“Laravel怎样自定义command命令浅析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

《Laravel怎样自定义command命令浅析.doc》

下载本文的Word格式文档,以方便收藏与打印。