1. 程式人生 > >laravel 開發輔助工具

laravel 開發輔助工具

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)


<h2>Excels匯出輔助外掛</h2>
<h3>外掛介紹</h3>
<p>Excels匯出輔助外掛</p>
<h3>建立 Excels</h3>

php artisan make:excel User


<p>上面命令會建立一個 AppExcelsModulesUserExcel::class 的類</p>
<h3>編寫Search</h3>

<?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-&gt;id,
        $this-&gt;phone,
        $this-&gt;name
    ];
}


/**
 * 搜尋引數
 * @return {[type]} [description]
 */
protected function getAttributes()
{
    return new ExcelSearch(request()-&gt;only([
        'phone',
        'name',
    ]));
}

}


<blockquote>更多用法 請參考 <a href="https://github.com/Maatwebsite/Laravel-Excel" rel="nofollow noreferrer">maatwebsite/excel</a>
</blockquote>
<h2>Sql 寫進日誌-事件</h2>
<h3>介紹</h3>
<p>把sql語句記錄到日誌裡</p>
<h3>使用</h3>
<p>在 laravel 自帶的 EventServiceProvider 類裡 listen 新增</p>

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


<h3>生成事件</h3>

php artisan event:generate


<h2>Controller Traits</h2>
<h3>介紹</h3>
<p>controller公用方法</p>
<h3>使用方法</h3>
<p>在 AppHttpControllersController 類中 use luffyzhaolaravelToolsTraitsResponseTrait</p>
<h2>Sign 加簽</h2>
<h3>外掛介紹</h3>
<p>請求引數加簽驗證</p>
<h3>配置 Sign</h3>
<p>如果你使用的是md5加簽方式請在config/app.php檔案中,新增 sign_key 配置。如果你使用的是Rsa加簽方式請在config/app.php檔案中,新增app.sign_rsa_private_key和app.sign_rsa_public_key配置</p>
<h3>配置中介軟體</h3>
<p>在app/Http/Kernel.php檔案中,您需要把 'sign' =&gt; luffyzhaolaravelToolsMiddlewareVerifySign::class, 新增到$routeMiddleware屬性中</p>
<h3>使用</h3>

<?php

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


<h5>加簽方式</h5>
<p><code>rsa</code> 和 <code>md5</code></p>
<h5>引數排序</h5>
<ul>
<li>準備引數</li>
<li>新增 <code>timestamp</code> 欄位</li>
<li>然後按照欄位名的 ASCII 碼從小到大排序(字典序)</li>
<li>生成 <code>url</code> 引數串</li>
<li>拼接 key 然後 md5 或者 rsa</li>
</ul>
<p>如下所示:</p>

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


<p>排序後:</p>

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


<p>生成url引數串:</p>
<blockquote>aimncm=54854185&amp;df4[0]=dfadsf&amp;dfsd3a=56fdg&amp;dfsd3a=56fdg&amp;name=4sd65f4asd5f4as5df&amp;timestamp=2018-05-29 17:25:34</blockquote>
<p>拼接 key :</p>
<blockquote>aimncm=54854185&amp;df4[0]=dfadsf&amp;dfsd3a=56fdg&amp;dfsd3a=56fdg&amp;name=4sd65f4asd5f4as5df&amp;timestamp=2018-05-29 17:25:34base64:Z9I7IMHdO+T9qD3pS492GWNxNkzCxinuI+ih4xC4dWY=</blockquote>
<p>md5加密</p>
<blockquote>ddab78e7edfe56594e2776d892589a9c</blockquote>
<h1>redis-token 認證</h1>
<h3>外掛介紹</h3>
<p>把token儲存在redis。同時支援登入過期時間設定,登入之前,登入之後事件處理。</p>
<h3>配置 Auth guard</h3>
<p>在 config/auth.php 檔案中,你需要將 guards/driver 更新為 redis-token:</p>

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

...

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


<h3>更改 Model</h3>
<p>如果需要使用 redis-token 作為使用者認證,我們需要對我們的 User 模型進行一點小小的改變,實現一個介面,變更後的 User 模型如下:</p>

<?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();
}
}


<h3>登入</h3>

/**
* 登入
* @method store
* @param StoreRequest $request

@return \Illuminate\Http\JsonResponse

@author [email protected]
*/
public function store(StoreRequest $request)
{
$token = auth('api')->attempt(
$request->only(['phone', 'password'])
);

      if (!$token) {
          return $this-&gt;respondWithError('使用者不存在,或者密碼不正確!');
      }
      
      return $this-&gt;respondWithToken((string) $token);
  }

<h3>退出</h3>

/**
* 退出登入.

@method logout

@return \Illuminate\Http\JsonResponse

@author [email protected]
*/
public function logout()
{
auth('api')->logout();

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

```

事件

方法

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