当前位置:首页 > CMS教程 > 其它CMS > 列表

Laravel如何自定义command命令浅析

发布:smiling 来源: PHP粉丝网  添加日期:2021-11-13 23:46:59 浏览: 评论:0 

这篇文章主要给大家介绍了关于Laravel如何自定义command命令的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Laravel具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧。

前言

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

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

自定义方法如下:

1.创建command类

  1. <?php 
  2.  
  3. namespace App\Console\Commands; 
  4.  
  5. use Illuminate\Console\GeneratorCommand; 
  6.  
  7. class ServiceMakeCommand extends GeneratorCommand 
  8. { 
  9.  /** 
  10.   * The console command name. 
  11.   * 
  12.   * @var string 
  13.   */ 
  14.  protected $name = 'make:service'; 
  15.  
  16.  /** 
  17.   * The console command description. 
  18.   * 
  19.   * @var string 
  20.   */ 
  21.  protected $description = 'Create a new service class'; 
  22.  
  23.  /** 
  24.   * The type of class being generated. 
  25.   * 
  26.   * @var string 
  27.   */ 
  28.  protected $type = 'Services'; 
  29.  
  30.  /** 
  31.   * Get the stub file for the generator. 
  32.   * 
  33.   * @return string 
  34.   */ 
  35.  protected function getStub() 
  36.  { 
  37.   return __DIR__.'/stubs/service.stub'; 
  38.  } 
  39.  
  40.  /** 
  41.   * Get the default namespace for the class. 
  42.   * 
  43.   * @param string $rootNamespace 
  44.   * @return string 
  45.   */ 
  46.  protected function getDefaultNamespace($rootNamespace) 
  47.  { 
  48.   return $rootNamespace."\Services"; 
  49.  } 
  50. } 

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

  1. <?php 
  2.  
  3. namespace DummyNamespace; 
  4.  
  5. class DummyClass  
  6. { 
  7.  public function __construct() 
  8.  { 
  9.  
  10.  } 
  11. } 

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

运行测试

php artisan make:service Web/TestService

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

Tags: Laravel command

分享到: