Ray Lee | 李宗叡
Learn or Die
Published in
15 min readJan 4, 2021

--

Photo by Sigmund on Unsplash

# 版本

Laravel 7.x

# 前言

我喜歡使用 Laravel 開發的感覺, 除了開發快速, 程式碼簡潔且優雅之外, Laravel 框架本身也是一個很好的學習參照物。 本篇主要將官方文件重點整理成 Q&A 的形式呈現, 原子化的概念, 這方式並不適用於每個人, 但若對你有幫助, 我會很開心。

# 目錄

Laravel — 官方文件原子化翻譯 — 目錄

# Introduction

Laravel HTTP Client 中, 如果要使用 CLI 安裝 guzzle, 該怎麼做?

composer require guzzlehttp/guzzle

# Making Requests

以下的 Laravel example code 的意思是?

  • Example:
<?php
use Illuminate\Support\Facades\Http;

$response = Http::get('http://test.com');
  • Answer: 對指定 url 發 GET request

Laravel HTTP Client 中, 以下 example 中的 $response 是哪個 class 的 instance?

  • Example:
<?php
$response->body() : string;
$response->json() : array;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;
  • Answer: Illuminate\Http\Client\Response

以下的 Laravel example code 的意思是?

  • Example:
<?php
return Http::get('http://test.com/users/1')['name'];
  • Answer: 直接取得 response 中的 key name 的 value

# Request Data

Laravel HTTP Client 中, 預設發 request 的 content type 是?

application/json

以下的 Laravel example code 的意思是?

  • Example:
<?php
$response = Http::post('http://test.com/users', [
'name' => 'Steve',
'role' => 'Network Administrator',
]);
  • Answer: 對指定 url 發 Post request, 帶著 array 內的 parameters

# Sending Form URL Encoded Requests

以下的 Laravel example code 的意思是?

  • Example:
<?php
$response = Http::asForm()->post('http://test.com/users', [
'name' => 'Sara',
'role' => 'Privacy Consultant',
]);
  • Answer: 使用 application/x-www-form-urlencoded 的方式發 Request

# Multi-Part Requests

以下的 Laravel example code 的意思是?

  • Example:
<?php
$response = Http::attach(
'attachment', file_get_contents('photo.jpg'), 'photo.jpg'
)->post('http://test.com/attachments');
  • Answer: 使用 attach method, 指定使用 multi-part 發送 request, arg1 為 field name, arg2 為檔案來源, arg3 為檔名

Laravel HTTP Client 中, 在以下的 multi-part example, 是用什麼方式來傳送檔案?

  • Example:
<?php
$photo = fopen('photo.jpg', 'r');

$response = Http::attach(
'attachment', $photo, 'photo.jpg'
)->post('http://test.com/attachments');
  • Answer: stream source

# Headers

以下的 Laravel example code 的意思是?

  • Example:
<?php
$response = Http::withHeaders([
'X-First' => 'foo',
'X-Second' => 'bar'
])->post('http://test.com/users', [
'name' => 'Taylor',
]);
  • Answer: 對指定的 url 發 post request, 帶著 ['name' => 'Taylor' parameters, 並定義 headers

# Authentication

以下的 Laravel example code 的意思是?

  • Example:
<?php
// Basic authentication...
$response = Http::withBasicAuth('taylor@laravel.com', 'secret')->post(...);
  • Answer: 發 post request, 並帶著 basic auth 需要的 account & secret

以下的 Laravel example code 的意思是?

  • Example:
<?php
// Digest authentication...
$response = Http::withDigestAuth('taylor@laravel.com', 'secret')->post(...);
  • Answer: 發 post request, 並定義 digest 需要的 auth 資料

# Bearer Tokens

以下的 Laravel example code 的意思是?

  • Example:
<?php
$response = Http::withToken('token')->post(...);
  • Answer: 使用 HTTP Client 發送 request, 並指定要帶過去的 bearer token

# Timeout

以下的 Laravel example code 的意思是?

  • Example:
<?php
$response = Http::timeout(3)->get(...);
  • Answer: 發 get request, 並設定 timeout 為 3 秒, 超過會觸發 Illuminate\Http\Client\ConnectionException

# Retries

以下的 Laravel example code 的意思是?

  • Example:
<?php
$response = Http::retry(3, 100)->post(...);
  • Answer: 發 post request, 如果不成功, 最多 retry 3 次, 每次間隔 100 milliseconds, 若失敗回傳 Illuminate\Http\Client\RequestException instance

# Error Handling

Laravel HTTP Client 中, 要是 request 出現 error, HTTP client 會立即 throw error 嗎?

不會

以下的 Laravel example code 的意思是?

  • Example:
<?php
$response->clientError();
  • Answer: 判斷 response status code 是否為 400 level

以下的 Laravel example code 的意思是?

  • Example:
<?php
// Determine if the status code was >= 200 and < 300...
$response->successful();
  • Answer: 當我使用 HTTP Client 對一個 endpoint 發送 request 後, 若是 request 出現 error, HTTP client 並不會立即 throw error, 使用 successful 可判斷 request status code 是否介於 200–299

以下的 Laravel example command 的意思是?

  • Example:
<?php
$response->serverError();
  • Answer: Laravel HTTP Client 中, 要是 request 出現 error, HTTP client 並不會立即 throw error, 使用 serverError() 可判斷 error 是否 500 level

# Throwing Exceptions

以下的 Laravel example code 的意思是?

  • Example:
<?php
$response = Http::post(...);

$response->throw();

return $response['user']['id'];
  • Answer: 當使用 HTTP client 時, 若有錯誤 Laravel 並不會自動 throw exception, 需使用 throw(), 若有錯誤 exception 會被 throw

Laravel HTTP Client 中, 在以下的 example 若是出現 client error or server error, 會拋出哪個 class 的 instance?

  • Example:
<?php
$response = Http::post(...);

// Throw an exception if a client or server error occurred...
$response->throw();

return $response['user']['id'];
  • Answer: Illuminate\Http\Client\RequestException

Laravel HTTP Client 中, 當出錯了, 拋出一個 Illuminate\Http\Client\RequestException instance 時, 可從該 instance 的哪個 public property 取得 response?

$response property

Laravel HTTP Client 中, 以下的 example 中, 若是沒有出現錯誤, 會拋出 exception 嗎?

  • Example:
<?php
return Http::post(...)->throw()->json();
  • Answer: 不會

# Guzzle Options

以下的 Laravel example code 的意思是?

  • Example:
<?php
$response = Http::withOptions([
'debug' => true,
])->get('http://test.com/users');
  • Answer: 對指定 url 發 get request, 並使用 withOptions() 定義 request option

# Testing

# Faking Responses

以下的 Laravel example code 的意思是?

  • Example:
<?php
use Illuminate\Support\Facades\Http;

Http::fake();

$response = Http::post(...);
  • Answer: 當使用 Http 的 fake() 並不帶任何參數時, 會發送一個 fake request, 並且都會 return status code 200 response

# Faking Specific URLs

以下的 Laravel example code 的意思是?

  • Example:
<?php
Http::fake([
// Stub a JSON response for GitHub endpoints...
'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),

// Stub a string response for Google endpoints...
'google.com/*' => Http::response('Hello World', 200, ['Headers']),
]);
  • Answer: 使用 fake(), 定義兩個分別來自 'github.com/*', 'google.com/*' 的 fake response

Laravel HTTP Client 中, 以下的 example 中的 * 代表的意思是?

wildcard

以下的 Laravel example code 的意思是?

  • Example:
<?php
Http::fake([
// Stub a JSON response for GitHub endpoints...
'github.com/*' => Http::response(['foo' => 'bar'], 200, ['Headers']),

// Stub a string response for all other endpoints...
'*' => Http::response('Hello World', 200, ['Headers']),
]);
  • Answer: 使用 fake() 定義 fake response, 只要不是 'github.com/*' 的 url 都回 '*' 的 fake response

# Faking Response Sequences

以下的 Laravel example code 的意思是?

  • Example:
<?php
Http::fake([
'github.com/*' => Http::sequence()
->push('Hello World', 200)
->push(['foo' => 'bar'], 200)
->pushStatus(404),
->whenEmpty(Http::response()),
]);
  • Answer: 使用 sequence(), 依序回傳指定的 response 當預先定義的 response 都回傳後, Laravel 預設會 throw exception, whenEmpty() 可以定義這個 exception

以下的 Laravel example code 的意思是?

  • Example:
<?php
Http::fakeSequence()
->push('Hello World', 200)
->whenEmpty(Http::response());
  • Answer: 使用 fakeSequence 定義有順序的 fake response, 但不定義 url

# Fake Callback

以下的 Laravel example code 的意思是?

  • Example:
<?php
Http::fake(function ($request) {
return Http::response('Hello World', 200);
});
  • Answer: 使用 fake(), 並帶入 closure, closure 內定義 fake response

# Inspecting Requests

以下的 Laravel example code 的意思是?

  • Example:
<?php
Http::fake();

Http::withHeaders([
'X-First' => 'foo',
])->post('http://test.com/users', [
'name' => 'Taylor',
'role' => 'Developer',
]);

Http::assertSent(function ($request) {
return $request->hasHeader('X-First', 'foo') &&
$request->url() == 'http://test.com/users' &&
$request['name'] == 'Taylor' &&
$request['role'] == 'Developer';
});
  • Answer:

使用 assertSent(), 斷言確實有發出 request 並包含定義的內容

以下的 Laravel example code 的意思是?

  • Example:
<?php
Http::fake();

Http::post('http://test.com/users', [
'name' => 'Taylor',
'role' => 'Developer',
]);

Http::assertNotSent(function (Request $request) {
return $request->url() === 'http://test.com/posts';
});
  • Answer: 使用 assertsent(), 斷言並未對 url http://test.com/posts 發 request, 若 closure return true, 則斷言失敗

以下的 Laravel example code 的意思是?

  • Example:
<?php
Http::fake();

Http::assertNothingSent();
  • Answer:

斷言沒有送出任何 request

--

--

Ray Lee | 李宗叡
Learn or Die

It's Ray. I do both backend and frontend, but more focus on backend. I like coding, and would like to see the whole picture of a product.