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([], '退出成功');
}

事件

方法

原文地址:https://segmentfault.com/a/1190000015903727

最新文章

  1. Linux学习之五--常用操作
  2. Redis系列四之复制
  3. 浅谈C++设计模式之单例模式
  4. 优化ABAP性能(摘录)
  5. 使用poi解析Excel
  6. 搭建hbase-0.94.26集群环境
  7. eclipse/myeclipse使用技巧
  8. Probability theory
  9. [Backbone]Make Backbone Better With Extensions
  10. System.Globalization.CultureInfo.InvariantCulture 解决不同地域字符串格式不同问题
  11. 玩转Spring Cloud之服务注册发现(eureka)及负载均衡消费(ribbon、feign)
  12. Yii2设计模式——设计模式简介
  13. elementUi中input输入字符光标在输入一个字符后,光标失去焦点
  14. linux文件查找find命令
  15. hive 中间会话临时文件自动清理脚本
  16. 最新java学习路线:含阶段性java视频教程完整版
  17. Neo4J 教程
  18. 第27章:MongoDB-索引--唯一索引
  19. 设计模式原则(5)--Law of Demeter(LoD)--迪米特法则
  20. 【Android】1.2 创建Android模拟器

热门文章

  1. 698C
  2. CSS里#和.以及大小写
  3. E20170603-ts
  4. goalng——time包学习
  5. xposed源码编译与集成
  6. xshell、xftp最新版下载方法
  7. ASP.NET XML文件
  8. JDBC和数据库连接池
  9. js中取整数的方法
  10. Microsoft SQL Server学习(六)--查询语句