Laravel Artisan 自定义创建service命令
注:不限于service,自定义创建文件命令
-
场景
改造laravel框架,增加service层
-
以vendor\laravel\framework\src\Illuminate\Foundation\Console\CastMakeCommand.php文件为例
<?php namespace Illuminate\Foundation\Console; use Illuminate\Console\GeneratorCommand; # 文件继承GeneratorCommand class CastMakeCommand extends GeneratorCommand { /** * 控制台展示名称 * * @var string */ protected $name = 'make:cast'; /** * 命令说明 * * @var string */ protected $description = 'Create a new custom Eloquent cast class'; /** * The type of class being generated. * * @var string */ protected $type = 'Cast'; /** * 获取生成器存根文件 * * @return string */ protected function getStub() { return $this->resolveStubPath('/stubs/cast.stub'); } /** * 解析到存根的完全限定路径 * * @param string $stub * @return string */ protected function resolveStubPath($stub) { return file_exists($customPath = $this->laravel->basePath(trim($stub, '/'))) ? $customPath : __DIR__.$stub; } /** * 获取类的默认名称空间 * * @param string $rootNamespace * @return string */ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace.'\Casts'; } }
-
开始创建service
-
创建command文件
php artisan make:command ServiceMakeCommand
-
修改ServiceMakeCommand文件继承GeneratorCommand类
class ServiceMakeCommand extends GeneratorCommand
-
修改命令行执行名称:$signature
$signature = 'make:service'
-
修改命令描述
$description = '创建service'
-
设置生成类的类型
$type = 'Service';
-
设置类的默认命名空间
protected function getDefaultNamespace($rootNamespace) { return $rootNamespace.'\Services'; }
-
创建生成模板,在app\Console\Commands\下创建一个命令模板目录stubs,设置stub模板文件位置
<?php namespace {{ namespace }}; class {{ class }} { public function index() { // } }
# 获取生成器模板文件 protected function getStub() { return $this->resolveStubPath('/stubs/service.stub'); }
-
运行php artisan查看
# 命令已经产生 make:service 创建service
-
创建服务
root@4015e6d872b9:/home/www/laravel-basics# php artisan make:service UserService Service created successfully.
-
完成了!!!