自己想偷懒然后就写了一个自定义的命令一键生成 增 删 改 查 等四个接口
php artisan create:logic Test Admin 测试通过命令一键生成增删改查命令此版本是laravel_7.x true
对于比较繁琐常规的一些接口而且参数都一样为什么我不能通过一个命令就直接生成呢
避免一些不必要的重复工作
来吧直接上源码
首先介绍一下我主要的目录结构其他没用的我就没写 本次测试的用的是laravel 7
私信 发你源码
app Console Commands CreateLogic.php //自定义命令的运行文件 Http Controllers //控制器文件夹 Admin v1//控制器文件夹v1目录 TestController.php//通过命令创建的Test控制器 Api v1//控制器文件夹v1目录 TestController.php//通过命令创建的Test控制器 Requests Admin UpTestRequest.php//表单验证文件 Api UpTestRequest.php//表单验证文件 Logic Admin Test.php//逻辑层文件 Api Test.php //逻辑层文件 Models Test.php//模型层文件
第一步是创建对应的模板
在项目的根目录stubs文件夹下创建7个模版文件
模型层基础内容 model.stub
<?phpnamespace DummyNamespace;class DummyClass extends BaseModel{ //}
控制器模板内容 my_controller.stub
<?phpnamespace App\Http\Controllers\{{controller_name}}\v1;use App\Http\Controllers\Controller;use App\Logic\{{controller_name}}\{{class_name}};use App\Http\Requests\{{controller_name}}\Up{{class_name}}Request;use App\Http\Requests\BaseIdRequest;use App\Http\Requests\BaseStateRequest;use Illuminate\Http\Request;class {{class_name}}Controller extends Controller{ //{{describe}} {{controller_default}}}
控制器业务模板内容 my_default_controller.stub
protected $model; public function __construct() { $this->model = new {{class_name}}(); } public function index(Request $request) { $info = array( 'name' => $request->input('name') ?? '', ); $list = $this->model->index($info, $request->limit, $request->offset, $request->merchant_id); success(array_merge($list, ['page' => $request->page, 'limit' => $request->limit, 'offset' => $request->offset])); } public function create(Up{{class_name}}Request $request) { $info = array( 'merchant_id' => $request->input('key_uid') ?? 0, 'name' => $request->input('name') ?? '', ); $id = $request->input('id') ?? 0; if ($id > 0) { $info['updated_at'] = $request->times; $this->model->update($id, $info); } else { $info['created_at'] = $request->times; $this->model->create($info); } } public function setState(BaseStateRequest $request) { $info = array('state' => $request->input('state') ?? 0, 'updated_at' => $request->times); $id = $request->input('id') ?? 0; $this->model->setState($id, $info); } public function show(BaseIdRequest $request) { $id = $request->input('id') ?? 0; $info = $this->model->show($id); success($info); } public function destroy(BaseIdRequest $request) { $id = $request->input('id') ?? 0; $this->model->destroy($id); }
逻辑层基础模板内容 my_logic.stub
<?phpnamespace App\Logic\{{namespace}};use App\Logic\Logic;use App\Models;class {{class_name}} extends Logic{ //--{{describe}} {{logic_default}}}
逻辑层业务模板内容 my_default_logic.stub
protected $model; public function __construct() { $this->model = app(Models\{{model_name}}::class); } public function index($info, $limit = 20, $offset = 1,$merchant_id=0) { $where = $this->model ->when($merchant_id>-1, function ($query) use ($info,$merchant_id) { return $query->where('merchant_id', $merchant_id); }) ->when(!empty($info['name']), function ($query) use ($info) { return $query->where('name', 'like', '%' . $info['name'] . '%'); }); $total = $where->count(); if ($total < 1) { return array('total' => 0, 'list' => []); } else { $list = $where->orderBy('created_at', 'desc') ->orderBy('updated_at', 'desc') ->limit($limit) ->offset($offset) ->get() ->toArray(); return array('total' => $total, 'list' => $list); } } public function create($info) { verifyRepetition($this->model, [['name', '=', $info['name']],['merchant_id', '=', $info['merchant_id']]]); try { $id = $this->model->insert($info); if ($id) { success(); } else { error(errorCode()::CREATE_NO, __('api.create_no')); } } catch (\Exception $e) { error(errorCode()::ERROR_CATCH, __('api.catch')); } } public function update($id, $info) { verifyRepetition($this->model, [['name', '=', $info['name']],['merchant_id', '=', $info['merchant_id']], ['id', '<>', $id]]); try { $is_exists = $this->model->where('id', $id)->exists(); if (!$is_exists) { error(errorCode()::is_exists, __('api.is_exists')); } $up_id = $this->model->where('id', $id)->update($info); if ($up_id) { success(); } else { error(errorCode()::UPDATE_NO, __('api.update_no')); } } catch (\Exception $e) { error(errorCode()::ERROR_CATCH, __('api.catch')); } } public function setState($id, $info) { $res = $this->model->where('id', $id)->update(['state' => $info['state'], 'updated_at' => $info['updated_at']]); if ($res) { success(); } else { error(); } } public function show($id) { $info = $this->model->find($id); if ($info) { return $info->toArray(); } else { return []; } } public function destroy($id) { if (!is_array($id)) { $id = [$id]; } $res = $this->model->whereIn('id', $id)->delete(); if ($res) { success(); } else { error(errorCode()::DELETE_NO, __('api.delete_no')); } } /** * 数字格式化存储 */ public function toNumberFormatter($info) { $info['price'] = toNum($info['price']); return $info; } /** * 数字可视化 */ public function humNumberFormatter($info) { $info['price'] = humanNum($info['price']); return $info; }
表单验证模板内容 my_request.stub
<?phpnamespace App\Http\Requests\{{controller_name}};use App\Http\Requests\BaseRequest;class Up{{class_name}}Request extends BaseRequest{ /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return false; } /** * Get the validation rules that apply to the request. * {{describe}} * @return array */ public function rules() { return [ 'name' => 'required|string', ]; } public function messages() { return [ "name.required" => "名称不能为空", "name.string" => "名称格式不对", ]; }}
路由模板内容 my_routes.stub
备注:下面的 (//addController) 和//--{{describe}} 这段注释千万不要删除后面会用到
//--{{describe}} $router->get('{{controller}}/index', '{{class_name}}@index')->name('{{controller_name}}.{{controller_name_str}}.index'); //列表 $router->post('{{controller}}/create', '{{class_name}}@create')->name('{{controller_name}}.{{controller_name_str}}.create'); //创建 $router->get('{{controller}}/show', '{{class_name}}@show')->name('{{controller_name}}.{{controller_name_str}}.show'); //详情 $router->post('{{controller}}/destroy', '{{class_name}}@destroy')->name('{{controller_name}}.{{controller_name_str}}.destroy'); //删除 //addController
模版创建好后,创建一个自定义 artisan命令
在根目录输入以下命令
备注: 后面的(CreateLogic) 这个是随便取得的一个命令文件名称 根据自己的需求可以自己取
运行完后会生成一个文件在 项目 app\Console\Commands\CreateLogic.php
php artisan make:command CreateLogic
CreateLogic.php文件创建好后在app\Console\Kernel.php文件中
在变量$commands 中添加刚刚创建的CreateLogic.php路径
protected $commands = [ \App\Console\Commands\CreateLogic::class, ];
现在我们就开始写主要的内容了
直接上代码自己复制下去自己研究不懂的欢迎留言
以下内容是在app\Console\Commands\CreateLogic.php文件中编辑的
不想看可以直接翻下面完整的代码
create:logic 这段的意思是命令名称写死的当然你也可以自己定义比如up:logic等等
{class_name} 这个是控制器类名称 比如TestController 那么你直接输入Test就可以了
{controller_name} 这个是模块名称 就是你要将这个控制器放到Admin/v1目录还是放到Api/v1 目录的文件夹中
{describe} 这个是控制器注释 比如这个控制器叫测试创建TestController控制器
{model?} 这个表示是否创建数据库,你要注意的是你的数据库名称跟你{class_name}是一致的,不给的话就不创建
protected $signature = 'create:logic {class_name} {controller_name} {describe} {model?}';
以下是app\Console\Commands\CreateLogic.php完整代码
<?phpnamespace App\Console\Commands;use Illuminate\Console\Command;use Illuminate\Support\Facades\Artisan;class CreateLogic extends Command{ /** * The name and signature of the console command. * * @var string */ protected $signature = 'create:logic {class_name} {controller_name} {describe} {model?}'; /** * The console command description. * * @var string */ protected $description = 'Create logic'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return int */ public function handle() { //获取参数 $args = $this->arguments(); //控制器模块名称 Admin Api $controller_name = $args['controller_name']; //控制器类名称 $class_name = $args['class_name']; //是否创建模型层 $model = $args['model']; //描述 $describe = $args['describe']; //创建模型层 if ($model) { $this->createModel($class_name, $describe); } //创建逻辑层 $this->createLogic($controller_name, $class_name, $describe); //创建控制层 $this->createController($controller_name, $class_name, $describe); $this->createRequest($controller_name, $class_name, $describe); //创建路由层 $this->createRoutes($controller_name, $class_name, $describe); $this->info('一键创建逻辑成功 春哥牛逼' ); } /** * 创建模型层 */ public function createModel($class_name, $describe = '') { //模型层文件地址 Artisan::call("make:model Models/{$class_name} -fm"); //清除视图缓存 } /** * 控制层创建 */ public function createController($controller_name, $class_name, $describe) { //文件地址 $logic_file = app_path() . '/Http/Controllers' . "/{$controller_name}" . '/v1/' . $class_name . 'Controller.php'; $logic_path = dirname($logic_file); //返回路径中的目录部分 //获取模板,替换变量 $controller = file_get_contents(base_path('/stubs/my_controller.stub')); $controller_default = file_get_contents(base_path('/stubs/my_default_controller.stub')); $source = str_replace('{{controller_name}}', $controller_name, $controller); $source = str_replace('{{controller_default}}', $controller_default, $source); $source = str_replace('{{class_name}}', $class_name, $source); $source = str_replace('{{describe}}', $describe, $source); $this->createFileSend($logic_file, $logic_path, $source, '控制层'); } /** * 创建逻辑层 */ public function createLogic($controller_name, $class_name, $describe = '') { //逻辑层文件地址 $logic_file = app_path() . '/Logic' . "/{$controller_name}/" . $class_name . '.php'; //命名空间 $logic_path = dirname($logic_file); //返回路径中的目录部分 //获取模板,替换变量 $logic = file_get_contents(base_path('/stubs/my_logic.stub')); $logic_default = file_get_contents(base_path('/stubs/my_default_logic.stub')); $source = str_replace('{{namespace}}', $controller_name, $logic); $source = str_replace('{{describe}}', $describe, $source); $source = str_replace('{{class_name}}', $class_name, $source); $source = str_replace('{{logic_default}}', $logic_default, $source); $source = str_replace('{{model_name}}', $class_name, $source); $this->createFileSend($logic_file, $logic_path, $source, '逻辑层'); } /** * 创建表单验证 */ public function createRequest($controller_name, $class_name, $describe = '') { //逻辑层文件地址 $logic_file = app_path() . '/Http/Requests' . "/{$controller_name}/Up" . $class_name . 'Request.php'; //命名空间 $logic_path = dirname($logic_file); //返回路径中的目录部分 //获取模板,替换变量 $request = file_get_contents(base_path('/stubs/my_request.stub')); $source = str_replace('{{controller_name}}', $controller_name, $request); $source = str_replace('{{class_name}}', $class_name, $source); $source = str_replace('{{describe}}', $describe, $source); $this->createFileSend($logic_file, $logic_path, $source, '表单验证层'); } /** * 创建路由 */ public function createRoutes($controller_name, $class_name, $describe) { //路由层文件地址 $controller = str_replace('_', '/', $this->toUnderScore($class_name)); //文件地址 $routes_file = base_path('routes\\' . strtolower($controller_name) . '.php'); $template = file_get_contents($routes_file); $default_method = file_get_contents(base_path('/stubs/my_routes.stub')); $source = str_replace('//addController', $default_method, $template); $source = str_replace('{{controller}}', $controller, $source); $source = str_replace('{{describe}}', $describe, $source); $source = str_replace('{{class_name}}', $class_name . 'Controller', $source); $controller_name_str = str_replace('/', '.', $controller); $source = str_replace('{{controller_name_str}}', $controller_name_str, $source); $source = str_replace('{{controller_name}}', strtolower($controller_name), $source); //写入 if (!file_put_contents($routes_file, $source)) { $this->error('路由层追加失败!'); exit; } $this->info('文件重新加载中............'); exec('composer dump-autoload'); //重新加载文件 $this->info('文件重新加载成功............'); Artisan::call('cache:clear'); //清除应用缓存 Artisan::call('route:cache'); //清除路由缓存 Artisan::call('config:cache'); //清除配置缓存 Artisan::call('view:cache'); //清除视图缓存 $this->info('缓存已清除'); } /** * 执行文件创建 */ public function createFileSend($logic_file, $logic_path, $source, $message = '') { //是否已存在相同文件 if (file_exists($logic_file)) { $this->error("{$message}文件已存在"); exit; } //创建 if (file_exists($logic_path) === false) { if (mkdir($logic_path, 0777, true) === false) { $this->error("{$message}目录" . $logic_path . '没有写入权限'); exit; } } //写入 if (!file_put_contents($logic_file, $source)) { $this->error("{$message}创建失败!"); exit; } $this->info("{$message}创建成功!"); } //驼峰命名转下划线命名 public function toUnderScore($str) { $dstr = preg_replace_callback('/([A-Z]+)/', function ($matchs) { return '_' . strtolower($matchs[0]); }, $str); return trim(preg_replace('/_{2,}/', '_', $dstr), '_'); }}
限制是路由器这里我们也要改一下,以下是完整代码
//addController 这个不要删除了这段是有用的
以下代码是在routes\api.php 文件中编辑的
<?phpuse Illuminate\Routing\Router;use Illuminate\Support\Facades\Route;Route::prefix('v1') ->namespace('Api\v1') ->name('api.v1.') ->group(function () { Route::middleware('throttle:100') ->group(function (Router $router) { //addController }); });
//addController 这个不要删除了这段是有用的
以下代码是在routes\admin.php 文件中编辑的
<?phpuse Illuminate\Routing\Router;use Illuminate\Support\Facades\Route;Route::prefix('v1') ->namespace('Admin\v1') ->name('admin.v1.') ->group(function () { Route::middleware('throttle:100') ->group(function (Router $router) { //addController }); });
以下代码是在app\Providers\RouteServiceProvider.php 文件中编辑的
<?phpnamespace App\Providers;use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;use Illuminate\Support\Facades\Route;class RouteServiceProvider extends ServiceProvider{ /** * This namespace is applied to your controller routes. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\Http\Controllers'; /** * The path to the "home" route for your application. * * @var string */ public const HOME = '/home'; /** * Define your route model bindings, pattern filters, etc. * * @return void */ public function boot() { // parent::boot(); } /** * Define the routes for the application. * * @return void */ public function map() { $this->mapApiRoutes(); $this->mapAdminRoutes(); $this->mapWebRoutes(); // } /** * Define the "web" routes for the application. * * These routes all receive session state, CSRF protection, etc. * * @return void */ protected function mapWebRoutes() { Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); } /** * Define the "api" routes for the application. * * These routes are typically stateless. * * @return void */ protected function mapApiRoutes() { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); } protected function mapAdminRoutes() { Route::prefix('admin') ->middleware('admin') ->namespace($this->namespace) ->group(base_path('routes/admin.php')); }}
那么现在就是见证奇迹的时刻
在项目根目录下打开cmd终端输入以下命令
php artisan create:logic Test Admin 测试通过命令一键生成增删改查命令此版本是laravel_7.x true
通过命令实现了一键生成 以下就是效果图
内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/119785.html