laravel神器教你一秒搞定增刪改查業務模塊-composer包query-common

laravel神器教你一秒搞定增刪改查業務模塊

還在爲了不斷寫增刪改查而煩惱不堪嘛?還在爲了重複寫代碼而頭疼嘛?這個laravel神器拯救你的大腦,解放你的雙手。讓你有更多的時間去寫出更好的代碼。

安裝

首先使用composer安裝

composer require thepatter/query-common

安裝之後創建一個command

php artisan make:command MakeQueryCommand

把下面的內容複製粘貼進去

<?php

namespace App\Console\Commands;

use Illuminate\Support\Str;
use InvalidArgumentException;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;

class MakeQueryCommand extends GeneratorCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'make:queryController';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new queryController class';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'QueryController';

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return resource_path('stubs/queryController.stub');
    }

    /**
     * Get the default namespace for the class.
     *
     * @param  string  $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.'\Http\Controllers';
    }

    /**
     * Build the class with the given name.
     *
     * Remove the base controller import if we are already in base namespace.
     *
     * @param  string  $name
     * @return string
     */
    protected function buildClass($name)
    {
        $controllerNamespace = $this->getNamespace($name);

        $replace = [];

        if ($this->option('model')) {
            $replace = $this->buildModelReplacements($replace);
        }

        $replace["use {$controllerNamespace}\Controller;\n"] = '';

        return str_replace(
            array_keys($replace), array_values($replace), parent::buildClass($name)
        );
    }

    /**
     * Build the model replacement values.
     *
     * @param  array  $replace
     * @return array
     */
    protected function buildModelReplacements(array $replace)
    {
        $modelClass = $this->parseModel($this->option('model'));

        if (! class_exists($modelClass)) {
            if ($this->confirm("A {$modelClass} model does not exist. Do you want to generate it?", true)) {
                $this->call('make:model', ['name' => $modelClass]);
            }
        }

        return array_merge($replace, [
            'DummyFullModelClass' => $modelClass,
        ]);
    }

    /**
     * Get the fully-qualified model class name.
     *
     * @param  string  $model
     * @return string
     */
    protected function parseModel($model)
    {
        // if (preg_match('([^A-Za-z0-9_/\\\\])', $model)) {
        //     throw new InvalidArgumentException('Model name contains invalid characters.');
        // }

        $model = trim(str_replace('/', '\\', $model), '\\');

        if (! Str::startsWith($model, $rootNamespace = $this->laravel->getNamespace())) {
            $model = $rootNamespace.$model;
        }

        return $model;
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['model', 'm', InputOption::VALUE_OPTIONAL, 'Generate a query controller for the given model.'],
        ];
    }
}

在resources文件夾下創建stubs文件夾,在stubs文件夾下面創建QueryController.stub文件,把下面內容複製粘貼進去

<?php

namespace DummyNamespace;

use Illuminate\Http\Request;
use DummyRootNamespaceHttp\Controllers\QueryList\QueryController;
use App\Exceptions\CommonException;

class DummyClass extends QueryController
{
    /**
     * 字典數組
     * ['表裏的字段名' => '字典code',...]
     */
    protected $dicArr = [];

    /**
     * 字段映射 可選,不填默認轉成下劃線格式
     * ['搜索字段' => '表字段',...]
     */
    protected $filedsAdapter = [];

    /**
     * 創建時候的字段映射 可選,不填默認轉成下劃線格式
     * ['輸入字段' => '表字段']
     */
    protected $createAdapter = [];

    //定義表名 格式: table as t
    protected $shortTableName;


    protected function getModel() {
        return new "DummyFullModelClass";
    }

    /*
     * 查詢列表
     * @route get.api/lists
     */
    public function getList(Request $request){
        try{
            //檢查頁碼,搜索條件等
            $this->pageValid();
            //返回數據
            return $this->success($this->pageList());
        } catch (Exception $ex) {
            
        }
        
    }  

    /**
     * 創建
     * @route post.api/info
     */
    function createInfo(Request $request) {
        try{
            //創建
            $this->create($request->all());
            return $this->success(true);
        }catch(Exception $ex) {

        }
    }

    /**
     * 更新
     * @route put.api/info/{id}
     */
    function updateInfo(Request $request, $id) {
        try{
            //查詢記錄
            $detail = $this->getModel()->find($id);
            if (empty($detail)) {
                //補充錯誤信息
                throw new CommonException();
            }
            //更新
            $this->update($id,$request->all());
            return $this->success(true);
        }catch(Exception $ex) {

        }
    }

    /**
     * 查詢一條記錄
     * @route get.api/info
     */
    function detail(Request $request) {
        try{
            $rules = [
                'id'=>'required',
            ];
            $messages = [
                'id.required'=>'id爲必填項',
            ];
            //驗證
            $this->valid($request, $rule, $messages);
            //查詢記錄
            $detail = $this->getModel()->find($id);
            if (empty($detail)) {
                //補充錯誤信息
                throw new CommonException();
            }
            return $this->success($detail);
        }catch(Exception $ex) {

        }
    }

    /**
     * 刪除一條記錄
     * @route delete.api/info/{id}
     */
    function deleteInfo(Request $request, $id) {
        try{
            //查詢記錄
            $model = $this->getModel();
            $detail = $model->find($id);
            if (empty($detail)) {
                //補充錯誤信息
                throw new CommonException();
            }
            //進行刪除
            $res = $model->where('id', $id)->delete();
            return $this->success(true);
        }catch(Exception $ex) {

        }
    }
        
}

創建業務邏輯

這時候執行創建的artisan命令就可以了

php artisan make:queryController your controller path -m your model path

這時候在你的Controller下面就會多出一個Controller文件,你只需要在路由中添加路由就可以了。

這個庫的github地址在下面,感興趣的朋友可以看一下。

https://github.com/Thepatterraining/queryCommon

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章