代码phplaravel使用stub配合laravel-excel实现后台运行的excel下载中心
Alon创建模板stub
建一个stub模板,用于下面使用
在resources下新建stubs目录用于存储
新建一个query-download.stub
| <?php
 namespace DummyNamespace;
 
 use App\Exports\QueryExport;
 
 class DummyClass extends QueryExport
 {
 
 public function headings(): array
 {
 
 return [
 
 ];
 }
 
 public function columns($row): array
 {
 
 return [
 
 ];
 }
 
 public function stringColumns(): array
 {
 
 return [
 
 ];
 }
 
 }
 
 | 
stub占位符介绍
stub文件中会有很多占位符,下面说几个,还有很多占位符,后面再熟悉一下
- DummyNamespace : 命名空间
- DummyRootNamespace : 根命名空间
- DummyClass : 类名
创建command命令
| php artisan make:command Make/Download
 | 
生成好的新的command,需要如下操作
- 修改继承GeneratorCommand类并必须实现getStub方法
- 移除自动生成的protected $signature改为protected $name,其中$name就是最后要执行的命令了
下面直接上代码
| <?php
 namespace App\Console\Commands\Make;
 
 use Illuminate\Console\GeneratorCommand;
 use Symfony\Component\Console\Input\InputOption;
 
 class Download extends GeneratorCommand
 {
 
 
 
 
 
 protected $name = 'make:download';
 
 
 
 
 
 
 protected $description = '生成下载中心';
 
 
 
 
 
 
 protected $type = 'Download';
 
 
 
 
 
 
 public function getStub(): string
 {
 if ($this->option('array')) {
 return base_path('resources/stubs/array-download.stub');
 }else{
 return base_path('resources/stubs/query-download.stub');
 }
 }
 
 
 
 
 
 
 
 
 protected function getDefaultNamespace($rootNamespace): string
 {
 return $rootNamespace . '\Exports';
 }
 
 
 
 
 
 
 
 protected function getOptions()
 {
 return [
 
 
 
 
 
 ['query', '', InputOption::VALUE_NONE, 'Generate an export for a query.'],
 ['array', 'a', InputOption::VALUE_NONE, 'Generate an export for an array.']
 ];
 }
 }
 
 | 
其他可用方法
| protected function buildClass($name){
 
 }
 
 
 protected function replaceNamespace(&$stub, $name)
 {
 
 }
 
 | 
使用
query类型测试
执行生成命令,生成query类型的下载器


array类型测试
执行生成命令,生成array类型的下载器


ok,就酱
`