1. 程式人生 > >laravel框架元件安裝教程(包含常用元件運用例項)

laravel框架元件安裝教程(包含常用元件運用例項)

laravel核心元件安裝

1.httpstatus安裝

Httpstatus包提供了一種簡單而有效的方法來檢索任何給定HTTP狀態程式碼的標準狀態文字。

可以獲取任何有效狀態文字的HTTP狀態程式碼。

還提供所有狀態程式碼作為常量,以便更好地閱讀程式碼。

安裝

composer require lukasoppermann/http-status

用法

$Httpstatus = new Lukasoppermann\Httpstatus\Httpstatus();

//

get status text from codeecho

$Httpstatus->getReasonPhrase(301); // Moved Permanently

//

get the status code by textecho

$Httpstatus->getStatusCode('Method Not Allowed'); //

405

//

check if status code existsecho

$Httpstatus->hasStatusCode(404); // trueecho $Httpstatus->hasStatusCode(601); // false

//

check if reason phrase existsecho

$Httpstatus->hasReasonPhrase('Method Not Allowed');

// trueecho $Httpstatus-

>hasReasonPhrase('Does not exist');

// false

//

determine the type (or "class") of the codeecho $Httpstatus->getResponseClass(503); //

Httpstatus::CLASS_SERVER_ERROR

為方便起見,此軟體包提供了一個包含所有狀態程式碼的介面。在開發處理HTTP狀態程式碼的類時,只需實現介面並開始使用常量而不是幻數來獲得更易讀和易懂的程式碼。

use Lukasoppermann\Httpstatus\Httpstatuscodes;

class Response implements Httpstatuscodes{

public function someMethod(){ // ... some logic return respond(self::HTTP_CREATED, $json); }

}

也可以直接使用介面中的常量。

use Lukasoppermann\Httpstatus\Httpstatuscodes as Status;

class UserTest{

public function test_create_new_user(){ $this->assertEquals(Status::HTTP_CREATED, $response->status()); } }

配置

add custom texts$Httpstatus = new Lukasoppermann\Httpstatus\Httpstatus([ 200 => 'Kein Inhalt', 404 => 'Nicht gefunden',]);

狀態程式碼的第一個數字定義了響應類。最後兩位數字沒有任何分類角色。第一個數字有五個值:

數字

類別

含義

1XX

資訊化

收到請求,繼續進行

2XX

成功

該請求已成功接收,理解和接受

3XX

重定向

需要採取進一步行動才能完成請求

4XX

客戶端錯誤

請求包含錯誤的語法或無法實現

5XX

伺服器錯誤

伺服器無法滿足明顯有效的請求

可用的HTTP狀態程式碼

資訊

RFC

100

繼續

[RFC7231,第6.2.1節]

101

切換協議

[RFC7231,第6.2.2節]

102

處理

[RFC2518]

103-199

未分配

200

[RFC7231,第6.3.1節]

201

建立

[RFC7231,第6.3.2節]

202

公認

[RFC7231,第6.3.3節]

203

非權威資訊

[RFC7231,第6.3.4節]

204

無內容

[RFC7231,第6.3.5節]

205

重置內容

[RFC7231,第6.3.6節]

206

部分內容

[RFC7233,第4.1節]

207

多型

[RFC4918]

208

已經報道過了

[RFC5842]

209-225

未分配

226

IM已使用

[RFC3229]

227-299

未分配

300

多種選擇

[RFC7231,第6.4.1節]

301

永久移動

[RFC7231,第6.4.2節]

302

發現

[RFC7231,第6.4.3節]

303

見其他

[RFC7231,第6.4.4節]

304

沒有修改

[RFC7232,第4.1節]

305

使用代理伺服器

[RFC7231,第6.4.5節]

306

(沒用過)

[RFC7231,第6.4.6節]

307

臨時重定向

[RFC7231,第6.4.7節]

308

永久重定向

[RFC7538]

309-399

未分配

400

錯誤的請求

[RFC7231,第6.5.1節]

401

擅自

[RFC7235,第3.1節]

402

需要付款

[RFC7231,第6.5.2節]

403

被禁止

[RFC7231,第6.5.3節]

404

未找到

[RFC7231,第6.5.4節]

405

方法不允許

[RFC7231,第6.5.5節]

406

不能接受的

[RFC7231,第6.5.6節]

407

需要代理驗證

[RFC7235,第3.2節]

408

請求超時

[RFC7231,第6.5.7節]

409

衝突

[RFC7231,第6.5.8節]

410

[RFC7231,第6.5.9節]

411

長度要求

[RFC7231,第6.5.10節]

412

前提條件失敗

[RFC7232,第4.2節]

413

有效載荷過大

[RFC7231,第6.5.11節]

414

URI太長了

[RFC7231,第6.5.12節]

415

不支援的媒體型別

[RFC7231,第6.5.13節]

416

範圍不滿意

[RFC7233,第4.4節]

417

期望失敗

[RFC7231,第6.5.14節]

418

我是一個茶壺

[RFC2324,第2.3.2節]

419-420

未分配

421

錯誤的請求

[RFC7540,第9.1.2節]

422

不可處理的實體

[RFC4918]

423

鎖定

[RFC4918]

424

失敗的依賴

[RFC4918]

425

保留給WebDAV高階集合過期的提案

426

需要升級

[RFC7231,第6.5.15節]

427

未分配

428

前提要求

[RFC6585]

429

請求太多

[RFC6585]

430

未分配

431

請求標頭欄位太大

[RFC6585]

432-499

未分配

500

內部伺服器錯誤

[RFC7231,第6.6.1節]

501

未實現

[RFC7231,第6.6.2節]

502

錯誤的閘道器

[RFC7231,第6.6.3節]

503

暫停服務

[RFC7231,第6.6.4節]

504

閘道器超時

[RFC7231,第6.6.5節]

505

不支援HTTP版本

[RFC7231,第6.6.6節]

506

變種也談判

[RFC2295]

507

儲存空間不足

[RFC4918]

508

檢測到環路

[RFC5842]

509

未分配

510

沒有擴充套件

[RFC2774]

511

需要網路驗證

[RFC6585]

512-599

未分配

2.Fractal安裝

Fractal為複雜的資料輸出提供了一個表示和轉換層,就像在RESTful API中找到的一樣,並且可以很好地與JSON一起使用。可以將其視為 JSON / YAML / etc的檢視層。

在構建API時,人們通常只是從資料庫中獲取內容並將其傳遞給json_encode()。對於“普通”API而言,這可能是可以接受的,但如果它們被公眾使用或被移動應用程式使用,那麼這將很快導致輸出不一致。

作用

在源資料和輸出之間建立保護遮蔽,因此架構更改不會影響使用者

系統的資料型別轉換,以避免foreach()貫穿(bool)始終

包含複雜資料結構的(也就是嵌入,巢狀或側面載入)關係

使用HAL和JSON-API等標準,但也允許自定義序列化

支援資料結果的分頁,適用於小型和大型資料集

通常可以簡化在非平凡API中輸出資料的微妙複雜性

安裝

composer require league/fractal

3.intervention/image安裝

Intervention Image是一個開源的PHP影象處理和操作庫。它提供了一種更簡單,更有表現力的方式來建立,編輯和組合影象,並支援目前最常見的兩個影象處理庫GD Library和Imagick。編寫該類是為了使PHP影象操作更容易,更具表現力。無論您是要建立影象縮圖,水印還是格式化大型影象檔案,Intervention Image都可以幫助您以儘可能少的程式碼行輕鬆管理每項任務。

安裝

composer require intervention/image

官方文件

4.Someline Rest API Client安裝

Someline Starter API Client是一款優雅且智慧的Rest API客戶端,具有OAuth2身份驗證支援。為Laravel和Someline Starter構建。

它可用於訪問使用Someline Starter框架建立的API 。

安裝

composer require someline/rest-api-client

新增服務提供商 config/app.php

'providers' => [ ...       Someline\Rest\RestClientServiceProvider::class,       ...  ],

釋出配置檔案

php artisan vendor:publish

釋出後,Rest Client的配置檔案是config/rest-client.php,您需要將其配置為使用Rest Client。

用法

$restClient = new \Someline\Rest\RestClient('someline-starter');

$restClient->setOAuthUserCredentials([ 'username' => '[email protected]', 'password' => 'Abc12345', ]); $restClient->withOAuthTokenTypeUser();

$response = $restClient->get("users")->getResponse();

if (!$restClient->isResponseStatusCode(200)) {

$restClient->printResponseOriginContent();

$responseMessage = $restClient->getResponseMessage();

print_r($responseMessage); }

else {

$responseData = $restClient->getResponseData();

print_r($responseData);

}

5.redis的安裝和配置

簡介

Redis是一個開源的、基於記憶體的資料結構儲存器,可以被用作資料庫、快取和訊息代理。相較Memcached而言,支援更加豐富的資料結構,包括字串、雜湊、列表、集合、有序集合等,此外還支援將資料持久化到資料庫。

安裝啟動Redis及依賴包

Laravel專案根目錄下執行如下命令使用Composer安裝predis依賴包:

composer require predis/predis 1.0.*

配置

前面我們已經提到Redis可以用作主資料庫,所以Laravel中Redis的配置資訊位於config/database.php中:

'redis' => [

'cluster' => false,

'default' => [

'host' => '127.0.0.1',

'port' => 6379,

'database' => 0,

],

],

其中cluster選項表示是否在多個Redis節點間進行分片,這裡我們本地測試只有一個節點故將其設定為false。

default選項表示預設Redis主機連線,這裡Redis和Web伺服器共用一臺主機,所以host為127.0.0.1,Redis預設埠是6379。

此外,default選項還支援更多連線引數(如果需要的話):

引數

意義

預設值

host

伺服器IP地址/主機名稱

127.0.0.1

port

Redis伺服器監聽的埠號

6379

password

如果伺服器需要認證密碼

不使用密碼

database

連線時選擇的資料庫索引

沒有設定索引

timeout

連線到Redis伺服器超時時間

5秒

read_write_timeout

通過網路連線進行讀寫操作的超時時間

系統預設(不限制超時時間的話設定為-1)

另外Redis如果是作為快取工具,還需要在config/cache.php配置redis選項:

'redis' => [

'driver' => 'redis',

'connection' => 'default',

],

基本使用

由於Laravel預設已經將Redis門面新增到config/app.php的aliases陣列中,所以在程式碼中可以直接使用該門面進行Redis操作。我們可以在Redis門面上以靜態方法的方式呼叫Redis客戶端提供的任何命令,然後Laravel使用魔術方法將命令傳遞給Redis伺服器並返回獲取的結果。

下面我們來看最簡單的讀取操作:

$key = 'user:name:6';

$user = User::find(6);

if($user){

//將使用者名稱儲存到Redis中

Redis::set($key,$user->name);

}

//判斷指定鍵是否存在

if(Redis::exists($key)){

//根據鍵名獲取鍵值

dd(Redis::get($key));

}

以上是簡單的字串存取,下面我們看一個更復雜的例子,將獲取到的資料存放到集合中:

$key = 'posts:title';

$posts = Post::all();

foreach ($posts as $post) {

//將文章標題存放到集合中

Redis::sadd($key,$post->title);

}

//獲取集合元素總數(如果指定鍵不存在返回0)

$nums = Redis::scard($key);

if($nums>0){

//從指定集合中隨機獲取三個標題

$post_titles = Redis::srandmember($key,3);

dd($post_titles);

}

6.GuzzleHTTP的安裝和配置

簡介

Guzzle是一個PHP HTTP客戶端,可以輕鬆傳送HTTP請求,並且可以輕鬆整合Web服務。

用於構建查詢字串,POST請求,流式傳輸大型上傳,流式傳輸大型下載,使用HTTP cookie,上傳JSON資料等的簡單介面...

可以使用相同的介面傳送同步和非同步請求。

為請求,響應和流使用PSR-7介面。這使您可以與Guzzle一起使用其他PSR-7相容庫。

抽象出底層的HTTP傳輸,允許您編寫環境和傳輸不可知的程式碼; 即不依賴於cURL,PHP流,套接字或非阻塞事件迴圈。

中介軟體系統允許您增強和編寫客戶端行為。

安裝

使用composer安裝

composer require guzzlehttp/guzzle

或者編輯專案的composer.json檔案,新增Guzzle作為依賴

{

"require":

{

"guzzlehttp/guzzle":"~6.0"

}

}

執行composer update

使用

傳送請求

use GuzzleHttp\Client;

$client = new Client([

// Base URI is used with relative requests

// You can set any number of default request options.

'timeout' => 2.0,

]);

設定查詢字串

或使用query 請求引數來宣告查詢字串引數:

$client->request('GET', 'http://httpbin.org', [

'query' => ['foo' => 'bar']

]);

設定POST表單

傳入form_params陣列引數

$response = $client->request('POST', 'http://httpbin.org/post', [

'form_params' => [

'field_name' => 'abc',

'other_field' => '123',

'nested_field' => [

'nested' => 'hello'

]

]

]);

使用響應

# 狀態碼

$code = $response->getStatusCode(); // 200

$reason = $response->getReasonPhrase(); // OK

# header

// Check if a header exists.

if ($response->hasHeader('Content-Length')) {

echo "It exists";

}

// Get a header from the response.

echo $response->getHeader('Content-Length');

// Get all of the response headers.

foreach ($response->getHeaders() as $name => $values) {

echo $name . ': ' . implode(', ', $values) . "\r\n";

}

# 響應體

$body = $response->getBody();

// Implicitly cast the body to a string and echo it

echo $body;

// Explicitly cast the body to a string

$stringBody = (string) $body;

// Read 10 bytes from the body

$tenBytes = $body->read(10);

// Read the remaining contents of the body as a string

$remainingBytes = $body->getContents();

7.Restful API的安裝

安裝

在laravel的根目錄的composer.json 檔案中引入

"dingo/api":"2.0.0-alpha1"

再執行

composer update

以在專案中包含最新版本的軟體包。

此時包裝仍處於發育階段,因此沒有穩定的釋放。您可能需要將您設定minimum-stability為dev。

安裝軟體包後,下一步取決於您使用的是哪個框架。

配置

如果您想在配置檔案中進行配置更改,可以使用以下Artisan命令釋出它:

php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"

流明

開啟bootstrap/app.php並註冊所需的服務提供商。

$app->register(Dingo\Api\Provider\LumenServiceProvider::class);

外立面

包裹隨附兩個外牆。您可以根據需要新增其中任何一個。

Dingo\Api\Facade\API

這是排程程式的外觀,但是,它還為整個程式包中的其他方法提供了輔助方法。

Dingo\Api\Facade\Route

這是API路由器的外觀,可用於獲取當前路由,請求,檢查當前路由名稱等。

8.L5  的安裝

安裝

執行以下命令以獲取最新版本的軟體包:

composer require prettus/l5-repository

Laravel> = laravel5.5

ServiceProvider將自動附加

其他

在您config/app.php新增

Prettus\Repository\Providers\RepositoryServiceProvider::class到providers陣列的末尾:

' providers ' => [ ... Prettus \ Repository \ Providers \ RepositoryServiceProvider :: class,],

如果流明

$ app - > register(Prettus \ Repository \ Providers \ LumenRepositoryServiceProvider :: class);

釋出

php artisan供應商:釋出--provider “ Prettus \ Repository \ Providers \ RepositoryServiceProvider ”

9.Laravel Validation的安裝

安裝

將“prettus / laravel-repository”:“1.1。*”新增到composer.json

"prettus/laravel-validation": "1.1.*"

再執行

composer update

以在專案中包含最新版本的軟體包。

配置

建立驗證器

Validator包含新增,編輯的規則。

Prettus \ Validator \ Contracts \ ValidatorInterface :: RULE_CREATE

Prettus \ Validator \ Contracts \ ValidatorInterface :: RULE_UPDATE

在下面的示例中,我們為建立和編輯定義了一些規則

use \ Prettus \ Validator \ LaravelValidator ;

class PostValidator extends LaravelValidator {

protected $ rules = [ ' title ' => ' required ',' text ' => ' min:3 ',' author ' => ' required ' ];

}

要定義特定規則,請按以下步驟操作:

use \ Prettus \ Validator \ LaravelValidator ;

class PostValidator extend LaravelValidator {

protected $ rules = [ ValidatorInterface :: RULE_CREATE => [ ' title ' => ' required ',' text ' => ' min:3 ',' author ' => ' required ' ],

ValidatorInterface :: RULE_UPDATE => [ ' title ' => ' required ' ] ];

自定義錯誤訊息

您可以使用自定義錯誤訊息進行驗證,而不是預設值

protected $ messages = [ ' required ' => ':屬性欄位是必需的。',];

或者,您可能希望僅為特定欄位指定自定義錯誤訊息。

protected $ messages = [ ' email.required ' => '我們需要知道您的電子郵件地址!',];

自定義屬性

您也可以使用自定義名稱屬性

protected $ attributes = [ ' email ' => '電子郵件',' obs ' => '觀察',];

使用驗證器

use \ Prettus \ Validator \ Exceptions \ ValidatorException ;

class PostsController wxtends BaseController {

/ ** * @var PostRepository * / protected $ repository ; / ** * @var PostValidator * / protected $ validator ;

public function __construct(PostRepository $ repository,PostValidator $ validator){ $ this - > repository = $ repository ; $ this - > validator = $ validator ; }

public function store() {

try {

$ this - > validator - > with(Input :: all())- > passesOrFail(); // OR $ this-> validator-> with(Input :: all()) - >

passesOrFail(ValidatorInterface :: RULE_CREATE);

$ post = $ this - > repository - > create(Input :: all());

return Response :: json([ ' message ' => ' Post created ',' data ' => $ post - > toArray() ]);

} catch(ValidatorException $ e){

return Response :: json([ ' error ' => true,' message ' => $ e - > getMessage() ]);

} }

public function update($id) {

try { $ this - > validator - > with(Input :: all())- > passesOrFail(ValidatorInterface :: RULE_UPDATE); $ post = $ this - > repository -

> update(Input :: all(),$ id);

return Response :: json([ ' message ' => ' Post created ',' data ' => $ post - > toArray() ]);

} catch(ValidatorException $ e){

return Response :: json([ ' error ' => true,' message ' => $ e - > getMessage() ]);

}

} }

10.Intervention Image Cache的安裝

安裝

使用composer 安裝

composer require intervention/imagecache

現在您可以要求vendor/autoload.phpPSR-4檔案自動載入庫了。

整合

Image Cache類支援Laravel整合。在Laravel中使用庫的最佳做法是新增干預影象類的ServiceProvider和Facade。

開啟Laravel配置檔案config/app.php並新增以下行。

在$providers陣列中新增此包的服務提供者。

'providers' => array(

[...]

'Intervention\Image\ImageServiceProvider'

),

將此包的外觀新增到$aliases陣列中。

'aliases' => array(

[...]

'Image' => 'Intervention\Image\Facades\Image'

),

用法

影象快取最好由Image::cacheIntervention Image類的靜態方法呼叫。

要建立快取影象,只需使用靜態方法Image::cache並通過閉包傳遞影象操作。該方法將自動檢測是否存在特定操作的快取檔案。

//在影象上執行操作或從快取中讀取檔案//用於特定操作$ img = Image :: cache( function( $ image){ return $ image - > make( ' public / foo.jpg ') - >調整大小( 300, 200) - >灰度();});

確定快取檔案的生命週期(以分鐘為單位)作為可選的第二個引數。將布林值true作為可選的第三個引數傳遞,以返回干預影象物件而不是影象流。

//確定壽命,並返回作為物件,而不是字串$ IMG = 圖片::快取(函式( $影象){返回$影象- >使( '公共/ foo.jpg ') - >調整

300, 200) - > greyscale();}, 10, true);

11.Someline Image Service的安裝

安裝

composer require someline/someline-image

新增服務提供商 config/app.php

' providers ' => [ ... Someline \ Image \ SomelineImageServiceProvider :: class, ... ],

釋出

php artisan vendor:publish

釋出後,Rest Client的配置檔案是config/someline-image.php,您需要將其配置為使用Rest Client。

用法

路由

Route :: get(' / image / {name} ',' ImageController @ showOriginalImage ');

Route :: post(' / image ',' ImageController @ postImage ');

許多影像

在模型上使用:

使用 SomelineHasImageablesTrait ;

用法:

/ * * @var SomelineImage $ somelineImage * / $ somelineImage = SomelineImage :: find( 1);

/ * * @var User $ user * / $ user = User :: find( 1);

//巧妙儲存影象關係與序列支援(推薦)$使用者- > syncImages([ 1, 2 ],[ '型別' => '蓋', '資料' => json_encode( '一個')]);

//通過save $ user - > images() - > save( $ somelineImage,[ ' type ' => ' cover ', ' data ' => json_encode( ' a ')])儲存影象關係 ;

//通過附加$ user - > images() - > attach( 1,[ ' type ' => ' cover ', ' data ' => json_encode( ' a ')])儲存影象關係 ;

//通過sync $ user - > images() - > sync([ 1 ])更新影象關係 ;

//設定為主影象$ user - > setAsMainImage( $ somelineImage);

//設定為主要影象$ user - > setAsTypeMainImage( ' cover ', $ somelineImage);

//獲取所有影象print_r( $ user - > getImages() - > toArray());

//獲取第一個主影象print_r( $ user - > getMainImage() - > toArray());

//獲取所有主要影象print_r( $ user - > getMainImages() - > toArray());

//獲取所有型別的影象print_r( $ user - > getTypeImages( ' cover ') - > toArray());

//獲取所有型別的影象並且是主要影象print_r( $ user - > getTypeMainImages( ' cover ') - > toArray());

示例控制器檔案

app/Http/Controllers/ImageController.php

<?php namespace App \ Http \ Controllers ;

使用 例外 ; 使用 Illuminate \ Http \ Request ; 使用 Someline \ Image \ Controllers \ SomelineImageController ; 使用 Someline \ Models \ Image \ SomelineImage ; 使用 Someline \ Image \ SomelineImageService ; class ImageController 擴充套件 Controller {

public function postImage(Request $ request) { $ somelineImageService = new SomelineImageService(); $ file = $ request - > file(' image ');

$ somelineImage = null ; 試試 { / * * @var SomelineImage $ somelineImage * / $ somelineImage = $ somelineImageService - > handleUploadedFile($ file); } catch(Exception $ e){ return '無法儲存:'。$ e - > getMessage(); } if(!$ somelineImage){ return '無法儲存上傳的圖片。' ; }

$ somelineImageId = $ somelineImage - > getSomelineImageId(); 返回'已儲存:'。$ somelineImage - > getImageUrl(); }

public function showOriginalImage($ image_name) { return SomelineImageController :: showImage(' original ',$ image_name); }

}

12.Laravel Passport的安裝

安裝

要開始,請通過Composer包管理器安裝Passport:

composer require laravel/passport

Passport服務提供程式使用框架註冊其自己的資料庫遷移目錄,因此您應在註冊提供程式後遷移資料庫。Passport遷移將建立應用程式儲存客戶端和訪問令牌所需的表:

php artisan migrate

如果你不打算使用護照的預設遷移,你應該呼叫的方法的方法。

Passport::ignoreMigrationsregisterAppServiceProviderphp artisan vendor:publish --tag=passport

接下來,您應該執行該命令。此命令將建立生成安全訪問令牌所需的加密金鑰。此外,該命令將建立“個人訪問”和“密碼授予”客戶端,這些客戶端將用於生成訪問令牌:passport:install

php artisan passport:install

執行此命令後,將特徵新增到模型中。此特徵將為您的模型提供一些輔助方法,允許您檢查經過身份驗證的使用者的令牌和範圍:Laravel\Passport\HasApiTokensApp\User

<?php

namespace App;

use Laravel\Passport\HasApiTokens;use Illuminate\Notifications\Notifiable;use Illuminate\Foundation\Auth\User as Authenticatab

class User extends Authenticatable{

use HasApiTokens, Notifiable;}

接下來,您應該在您的方法中呼叫該方法。此方法將註冊發出訪問令牌和撤銷訪問令牌,客戶端和個人訪問令牌所需的路由:Passport::routesbootAuthServiceProvider

<?php

namespace App\Providers;

use Laravel\Passport\Passport;use Illuminate\Support\Facades\Gate;use Illuminate\Foundation\Support\Providers\AuthServiceProvi

class AuthServiceProvider extends ServiceProvider{

/**

  • The policy mappings for the application.

  • @var array

*/

protected $policies = [

'App\Model' => 'App\Policies\ModelPolicy',

];

/**

  • Register any authentication / authorization services.

  • @return void

*/

public function boot()

{

$this->registerPolicies();

Passport::routes();

}}

最後,在配置檔案中,您應該將身份驗證防護的選項設定為。這將指示您的應用程式在驗證傳入的API請求時使用 Passport :config/auth.phpdriverapipassportTokenGuard

'guards' => [

'web' => [

'driver' => 'session',

'provider' => 'users',

],

'api' => [

'driver' => 'passport',

'provider' => 'users',

],],

元件的使用

1.httpstatus外掛的使用

常用HttpStatus狀態:

HttpStatus.OK = 200;

HttpStatus.BADREQUEST = 400;

HttpStatus.FORBIDDEN = 403;

HttpStatus.NOTFOUND = 404;

HttpStatus.TIMEOUT = 408;

HttpStatus.SERVERERROR = 500;

用法

$Httpstatus = new Lukasoppermann\Httpstatus\Httpstatus();

// get status text from codeecho $Httpstatus->getReasonPhrase(301); // Moved Permanently

// get the status code by textecho $Httpstatus->getStatusCode('Method Not Allowed'); // 405

// check if status code existsecho $Httpstatus->hasStatusCode(404); // trueecho $Httpstatus->hasStatusCode(601); // false

// check if reason phrase existsecho $Httpstatus->hasReasonPhrase('Method Not Allowed'); // trueecho $Httpstatus->hasReasonPhrase('Does not exist'); // false

// determine the type (or "class") of the codeecho $Httpstatus->getResponseClass(503); // Httpstatus::CLASS_SERVER_ERROR

$Httpstatus = new Lukasoppermann\Httpstatus\Httpstatus(); echo $Httpstatus->getReasonPhrase(301); echo "<pre>";

echo $Httpstatus->getStatusCode('Method Not Allowed');

2.Fractal元件的使用

例項

為了簡單起見,這個例子被放在一起,就像它是一個檔案一樣。實際上,您可以將管理器初始化、資料收集和JSON轉換擴充套件到應用程式的單獨部分。

<?php

use League\Fractal\Manager;use League\Fractal\Resource\Collection;

  • Create a top level instance somewhere $fractal = new Manager();

  • Get data from some sort of source

  • Most PHP extensions for SQL engines return everything as a string, historically

  • for performance reasons. We will fix this later, but this array represents that.

$books = [

[

'id' => '1',

'title' => 'Hogfather', 'yr' => '1998',

'author_name' => 'Philip K Dick', 'author_email' => '[email protected]', ],

[

'id' => '2',

'title' => 'Game Of Kill Everyone', 'yr' => '2014',

'author_name' => 'George R. R. Satan', 'author_email' => '[email protected]', ]];

  • Pass this array (collection) into a resource, which will also have a "Transformer"

  • This "Transformer" can be a callback or a new instance of a Transformer object

  • We type hint for array, because each item in the $books var is an array

$resource = new Collection($books, function(array $book) {

return [

'id' => (int) $book['id'],

'title' => $book['title'],

'year' => (int) $book['yr'],

'author' => [

'name' => $book['author_name'],

'email' => $book['author_email'],

],

'links' => [

[

'rel' => 'self',

'uri' => '/books/'.$book['id'],

]

]

];});

  • Turn that into a structured array (handy for XML views or auto-YAML converting) $array = $fractal->createData($resource)->toArray();

  • Turn all of that into a JSON string

echo $fractal->createData($resource)->toJson();

// Outputs: {"data":[{"id":1,"title":"Hogfather","year":1998,"author":{"name":"Philip K Dick","email":"[email protected]"}},{

值得注意的是,回撥是一個相當劣質的替代使用真正的變壓器。它們允許您重用變壓器並保持控制器重量輕。

3.intervention/image元件的使用

用法

新增服務提供商 config/app.php

'providers' => [ ...       Someline\Rest\RestClientServiceProvider::class,       ...  ],

釋出配置檔案

php artisan vendor:publish

釋出後,Rest Client的配置檔案是config/rest-client.php,您需要將其配置為使用Rest Client。

4.Someline Rest API Client元件的使用

用法

$ restClient

= new \ Someline \ Rest \ RestClient(' someline-starter ');

$ restClient

- > setOAuthUserCredentials([ ' username ' => '[email protected]','

password ' => ' Abc12345 ',]); $ restClient - > withOAuthTokenTypeUser();

$ response = $ restClient - > get(“ users ”)- > getResponse();

if(!$ restClient - > isResponseStatusCode(200)){

$ restClient - > printResponseOriginContent();

$ responseMessage = $ restClient - > getResponseMessage();

print_r($ responseMessage);

} else {

$ responseData = $ restClient - > getResponseData();

        print_r($ responseData);

}

5.redis元件的使用

配置

前面我們已經提到Redis可以用作主資料庫,所以Laravel中Redis的配置資訊位於config/database.php中:

'redis' => [

'cluster' => false,

'default' => [

'host' => '127.0.0.1',

'port' => 6379,

'database' => 0,

],

],

其中cluster選項表示是否在多個Redis節點間進行分片,這裡我們本地測試只有一個節點故將其設定為false。

default選項表示預設Redis主機連線,這裡Redis和Web伺服器共用一臺主機,所以host為127.0.0.1,Redis預設埠是6379。

此外,default選項還支援更多連線引數(如果需要的話):

引數

意義

預設值

host

伺服器IP地址/主機名稱

127.0.0.1

port

Redis伺服器監聽的埠號

6379

password

如果伺服器需要認證密碼

不使用密碼

database

連線時選擇的資料庫索引

沒有設定索引

timeout

連線到Redis伺服器超時時間

5秒

read_write_timeout

通過網路連線進行讀寫操作的超時時間

系統預設(不限制超時時間的話設定為-1)

另外Redis如果是作為快取工具,還需要在config/cache.php配置redis選項:

'redis' => [

'driver' => 'redis',

'connection' => 'default',

],

用法

6.GuzzleHTTP元件的使用

用法

7.Restful API元件的使用

示例

RESTful API的開發和使用,無非是客戶端向伺服器發請求(request),以及伺服器對客戶端請求的響應(response)。本真RESTful架構風格具有統一介面的特點,即,使用不同的http方法表達不同的行為:

GET(SELECT):從伺服器取出資源(一項或多項)

POST(CREATE):在伺服器新建一個資源

PUT(UPDATE):在伺服器更新資源(客戶端提供完整資源資料)

PATCH(UPDATE):在伺服器更新資源(客戶端提供需要修改的資源資料)

DELETE(DELETE):從伺服器刪除資源

客戶端會基於GET方法向伺服器傳送獲取資料的請求,基於PUT或PATCH方法向伺服器傳送更新資料的請求等,服務端在設計API時,也要按照相應規範來處理對應的請求,這點現在應該已經成為所有RESTful API的開發者的共識了,而且各web框架的request類和response類都很強大,具有合理的預設設定和靈活的定製性。

常用的Response要包含的資料和狀態碼(status code)

當GET, PUT和PATCH請求成功時,要返回對應的資料,及狀態碼200,即SUCCESS

當POST建立資料成功時,要返回建立的資料,及狀態碼201,即CREATED

當DELETE刪除資料成功時,不返回資料,狀態碼要返回204,即NO CONTENT

當GET 不到資料時,狀態碼要返回404,即NOT FOUND

任何時候,如果請求有問題,如校驗請求資料時發現錯誤,要返回狀態碼 400,即BAD REQUEST

當API 請求需要使用者認證時,如果request中的認證資訊不正確,要返回狀態碼 401,即NOT AUTHORIZED 當API 請求需要驗證使用者許可權時,如果當前使用者無相應許可權,要返回狀態碼 403,即FORBIDDEN

如果你正在使用 Laravel 你可以使用下面的 Artisan 命令來發布配置檔案:

php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"

你可以在你的 .env 檔案中配置這個。字首

API_PREFIX=api

版本號

API_VERSION=v1

響應格式

API_DEFAULT_FORMAT=json

調式模式

API_DEBUG=true

版本組

為了避免與你主要的專案路由衝突,dingo/api 將會使用其專屬的路由例項。要建立端點,我們首先需要獲得一個 API 路由的例項:

$api = app('Dingo\Api\Routing\Router');

現在我們必須定義一個版本分組。這種定義方式有利於後續為相同端點新增多版本支援。

$api->version('v1', function ($api) {});

如果你想一個分組返回多個版本,只需要傳遞一個版本陣列。

$api->version(['v1', 'v2'], function ($api) {});

通過在第二個引數上傳遞一個屬性陣列,你也可以將此組視為特定框架的標準組。

$api->version('v1', ['middleware' => 'foo'], function ($api) {});

你還可以巢狀常規組以進一步定製某些端點。

$api->version('v1', function ($api) {$api->group(['middleware' => 'foo'], function ($api) {// Endpoints registered here will have the "foo" middleware applied.});});

建立端點

一旦你有了一個版本分組,你就可以在分組閉包的引數中,通過 $api 建立端點。

$api->version('v1',function($api){$api->get('users/{id}', 'App\Api\Controllers\UserController@show');});

因為端點被每個版本分組了,你可以為相同 URL 上的同一個端點建立不同響應。