laravel 开发辅助工具

皇甫端
• 阅读 1946

laravel 开发辅助工具

配置

添加服务提供商

将下面这行添加至 config/app.php 文件 providers 数组中:

'providers' => [
  ...
  App\Plugins\Auth\Providers\LaravelServiceProvider::class
 ]

插件及文档

Repository 模式

插件介绍

首先需要声明的是设计模式和使用的框架以及语言是无关的,关键是要理解设计模式背后的原则,这样才能不管你用的是什么技术,都能够在实践中实现相应的设计模式。

按照最初提出者的介绍,Repository 是衔接数据映射层和领域层之间的一个纽带,作用相当于一个在内存中的域对象集合。客户端对象把查询的一些实体进行组合,并把它 们提交给 Repository。对象能够从 Repository 中移除或者添加,就好比这些对象在一个 Collection 对象上进行数据操作,同时映射层的代码会对应的从数据库中取出相应的数据。

从概念上讲,Repository 是把一个数据存储区的数据给封装成对象的集合并提供了对这些集合的操作。

Repository 模式将业务逻辑和数据访问分离开,两者之间通过 Repository 接口进行通信,通俗点说,可以把 Repository 看做仓库管理员,我们要从仓库取东西(业务逻辑),只需要找管理员要就是了(Repository),不需要自己去找(数据访问),具体流程如下图所示:

创建 Repository

不使用缓存
php artisan make:repo User
使用缓存
php artisan make:repo User --cache
创建 UserRepository 时会询问是否创建Model ,如果Model以存在,需要把 AppRepositoriesModulesUserProvider::class 的Model替换成当前使用的Model

配置Providers

将下面这行添加至 AppProvidersAppServiceProvider::class 文件 register 方法中:

public function register()
{
    $this->app->register(\App\Repositories\Modules\User\Provider::class);
}

使用

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\Modules\User\Interfaces;

class HomeController extends Controller
{

    protected $repo = null;

    public function __construct(Interfaces $repo)
    {
        $this->repo = $repo;
    }

    public function index(Request $request){
        return $this->respondWithSuccess($this->repo->get(['*']));
    }
}
配合 Search 更灵活
public function index(Request $request){
        return $this->respondWithSuccess(
            $this->repo->getwhere(
                new IndexSearch($request->olny(['name'])) ,
                ['*']
            )
        );
    }

方法

参考 Repository 方法

表单搜索辅助插件

插件介绍

把表单提交的一些参数传换成 where 语句.

创建 Search

生成一个UserController::index控制器使用的搜索辅助类

php artisan make:search User\IndexSearch

上面命令会创建一个 AppSearchsModulesUserIndexSearch::class 的类

创建Search时,建议根据 ControllerActionSearch 的格式创建。

编写Search

<?php

namespace App\Searchs\Modules\User;

use luffyzhao\laravelTools\Searchs\Facades\SearchAbstract;

class IndexSearch extends SearchAbstract
{
    protected $relationship = [
        'phone' => '=',
        'name'  => 'like',
        'date' => 'between'
    ];
        
    public function getNameAttribute($value)
    {
        return $value . '%';
    }
    
    public function getDateAttribute($value){
        return function ($query){
            $query->where('date', '>', '2018-05-05')->where('status', 1);
        };
    }
}

使用Search

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\Modules\User\Interfaces;
use App\Searchs\Modules\User\IndexSearch;

class HomeController extends Controller
{

    protected $repo = null;

    public function __construct(Interfaces $repo)
    {
        $this->repo = $repo;
    }

    public function index(Request $request){
        return $this->respondWithSuccess(
            $this->repo->getWhere(
                new IndexSearch(
                    $request->only(['phone', 'name', 'date'])
                ), 
                ['*']
            )
          );
    }
}

生成的sql

请求参数:

phone=18565215214&name=成龙&date=2018-08-21

生成的sql

WHERE (phone = 18565215214) AND (name like '成龙%') AND (date > '2018-05-05' AND status = 1)

Excels导出辅助插件

插件介绍

Excels导出辅助插件

创建 Excels

php artisan make:excel User

上面命令会创建一个 AppExcelsModulesUserExcel::class 的类

编写Search

<?php
namespace App\Excels\Modules;


use App\Excels\Facades\ExcelAbstract;
use App\Repositories\Modules\User\Interfaces;
use App\Searchs\Modules\User\ExcelSearch;

class CarExcel extends ExcelAbstract
{

    public function __construct(Interfaces $repo)
    {
        parent::__construct($repo);
    }




    /**
     * Excel标题列
     * @return {[type]} [description]
     */
    public function headings()
    {
        return ['ID','手机号码','姓名'];
    }


    /**
     * @param mixed $row
     *
     * @return array
     */
    public function map($row)
    {
        return [
            $row->id,
            $this->phone,
            $this->name
        ];
    }


    /**
     * 搜索参数
     * @return {[type]} [description]
     */
    protected function getAttributes()
    {
        return new ExcelSearch(request()->only([
            'phone',
            'name',
        ]));
    }


}
更多用法 请参考 maatwebsite/excel

Sql 写进日志-事件

介绍

把sql语句记录到日志里

使用

在 laravel 自带的 EventServiceProvider 类里 listen 添加

 'Illuminate\Database\Events' => [
    'luffyzhao\laravelTools\Listeners\QueryListeners'
 ]

生成事件

php artisan event:generate

Controller Traits

介绍

controller公用方法

使用方法

在 AppHttpControllersController 类中 use luffyzhaolaravelToolsTraitsResponseTrait

Sign 加签

插件介绍

请求参数加签验证

配置 Sign

如果你使用的是md5加签方式请在config/app.php文件中,添加 sign_key 配置。如果你使用的是Rsa加签方式请在config/app.php文件中,添加app.sign_rsa_private_key和app.sign_rsa_public_key配置

配置中间件

在app/Http/Kernel.php文件中,您需要把 'sign' => luffyzhaolaravelToolsMiddlewareVerifySign::class, 添加到$routeMiddleware属性中

使用

<?php

Route::group(
    ['middleware' => 'sign:api'],
    function($route){
        Route::get('xxx', 'xxx');
    }
);
加签方式

rsamd5

参数排序
  • 准备参数
  • 添加 timestamp 字段
  • 然后按照字段名的 ASCII 码从小到大排序(字典序)
  • 生成 url 参数串
  • 拼接 key 然后 md5 或者 rsa

如下所示:

{
    "name": "4sd65f4asd5f4as5df",
    "aimncm": "54854185",
    "df4": ["dfadsf"],
    "dfsd3": {
        "a": {
            "gfdfsg": "56fdg",
            "afdfsg": "56fdg"
        }
    }
}

排序后:

{
    "aimncm": "54854185",
    "df4": ["dfadsf"],
    "dfsd3": {
        "a": {
            "afdfsg": "56fdg",
            "gfdfsg": "56fdg"
        }
    },
    "name": "4sd65f4asd5f4as5df",
    "timestamp": "2018-05-29 17:25:34"
}

生成url参数串:

aimncm=54854185&df4[0]=dfadsf&dfsd3a=56fdg&dfsd3a=56fdg&name=4sd65f4asd5f4as5df&timestamp=2018-05-29 17:25:34

拼接 key :

aimncm=54854185&df4[0]=dfadsf&dfsd3a=56fdg&dfsd3a=56fdg&name=4sd65f4asd5f4as5df&timestamp=2018-05-29 17:25:34base64:Z9I7IMHdO+T9qD3pS492GWNxNkzCxinuI+ih4xC4dWY=

md5加密

ddab78e7edfe56594e2776d892589a9c

redis-token 认证

插件介绍

把token保存在redis。同时支持登录过期时间设置,登录之前,登录之后事件处理。

配置 Auth guard

在 config/auth.php 文件中,你需要将 guards/driver 更新为 redis-token:

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

...

'guards' => [
    'api' => [
        'driver' => 'redis-token',
        'provider' => 'users',
    ],
],

更改 Model

如果需要使用 redis-token 作为用户认证,我们需要对我们的 User 模型进行一点小小的改变,实现一个接口,变更后的 User 模型如下:

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use luffyzhao\laravelTools\Auths\Redis\RedisTokeSubject;

class User extends Authenticatable implements RedisTokeSubject
{
    public function getIdentifier(){
        return $this->getKey();
    }
}

登录

  /**
       * 登录
       * @method store
       * @param StoreRequest $request
       *
       * @return \Illuminate\Http\JsonResponse
       *
       * @author luffyzhao@vip.126.com
       */
      public function store(StoreRequest $request)
      {
          $token = auth('api')->attempt(
              $request->only(['phone', 'password'])
          );
          
          if (!$token) {
              return $this->respondWithError('用户不存在,或者密码不正确!');
          }
          
          return $this->respondWithToken((string) $token);
      }

退出

/**
     * 退出登录.
     *
     * @method logout
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * @author luffyzhao@vip.126.com
     */
    public function logout()
    {
        auth('api')->logout();

        return $this->respondWithSuccess([], '退出成功');
    }

事件

方法

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
KaliTools说明书+BurpSuit实战指南+SQL注入知识库+国外渗透报告
!(https://oscimg.oschina.net/oscnet/d1c876a571bb41a7942dd9752f68632e.gif"15254461546.gif")0X00KaliLinux Tools中文说明书!(https://oscimg.oschina.net/oscnet/
Wesley13 Wesley13
3年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
3年前
MySQL总结(十一)子查询
!(https://oscimg.oschina.net/oscnet/upa344f41e81d3568e3310b5da00c57ced8ea.png)子查询1\.什么是子查询需求:查询开发部中有哪些员工selectfromemp;通
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
3年前
ELK学习笔记之配置logstash消费kafka多个topic并分别生成索引
0x00 filebeat配置多个topicfilebeat.prospectors:input_type:logencoding:GB2312fields_under_root:truefields:添加字段
Wesley13 Wesley13
3年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
美凌格栋栋酱 美凌格栋栋酱
4个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(