生成 Transformer (变形文件)的命令 版本5.7
2019年8月21日1.生成命令文件
1 |
php artisan make:command MakeTransformer |
2.编辑生成文件app/Console/Commands/MakeTransformer.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
<?php namespace App\Console\Commands; use Illuminate\Support\Str; use Illuminate\Console\GeneratorCommand; class MakeTransformer extends GeneratorCommand { /** * The name and signature of the console command. * * @var string */ protected $signature = 'make:transformer {name}'; /** * The console command description. * * @var string */ protected $description = '创建 transformer 变形文件'; /** * @return string */ protected function getStub() { return __DIR__.'/stubs/transformer'; } /** * @param $name * @return string */ protected function getPath($name) { $name = Str::replaceFirst($this->rootNamespace(), '', $name); return $this->laravel['path'].'/'.str_replace('\\', '/', $name).'Transformer.php'; } /** * @param $name * @return mixed */ protected function buildClass($name) { $stub = $this->files->get($this->getStub()); return $this->replaceClass($this->replaceInstance($stub, $name), $name); } /** * @param $stub * @param $name * @return mixed */ protected function replaceInstance($stub, $name) { $class = str_replace($this->getNamespace($name).'\\', '', $name); return str_replace('dummyInstance', lcfirst($class), $stub); } /** * @param $rootNamespace * @return string */ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace.'\Transformers'; } } |
3.创建模板文件app/Console/Commands/stubs/transformer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php namespace App\Transformers; use App\Models\DummyClass; use League\Fractal\TransformerAbstract; class DummyClassTransformer extends TransformerAbstract { public function transform(DummyClass $dummyInstance) { return [ 'id' => $dummyInstance->id, ]; } } |
4.使用命令 ,可以没有后缀
1 |
php artisan make:transformer {name} |
文件路径app/Transformers/{name}.php