WLCURL

Let PHP Api (CURL) request more easyly、clearly、liberty and modelly
讓 PHP Api (CURL) 請求更加簡單、清楚易懂、自由、模組化

WLCURL Installation - 安裝 Quick Example - 快速範例 Construct - 構成式 method base_url end_point url_para body header token token_type para_type opt Execute - 執行 exe Error Handle - 錯誤處理 is_error is_client_error is_bad_request is_unauthorized is_forbidden is_method_not_allow is_server_error Get Request Result - 取得請求結果 getBody getdecodeBody Modelly-Best Advance Practice - 模組化-最佳進階做法 File Structure - 檔案結構 MyApiServerApi TargetApi

Installation - 安裝

$ composer require weilun/wlcurl

Quick Example - 快速範例

use WeiLun/WLCURL; $order_api = new WLCURL; // Default GET method $order_api->base_url('https://my_api_server_url'); $order_api->end_point('/order'); $order_api->url_para(['page' => 1, 'page_size' => 24]); $order_api->exe();

Same as - 如下同上

use WeiLun/WLCURL; $order_api = (new WLCURL) // Default GET method ->base_url('https://my_api_server_url'); ->end_point('/order'); ->url_para(['page' => 1, 'page_size' => 24]); ->exe();

Same as - 如下同上

use WeiLun/WLCURL; $order_api = WLCURL::get([ 'base_url' => 'https://my_api_server_url', 'end_point' => '/order', 'url_para' => ['page' => 1, 'page_size' => 24] ])->exe();

Same as above but modelly - 如下同上但模組化

use WeiLun/WLCURL; class MyApiServerApi extends WLCURL { function __construct($para) { $this->base_url = 'https://my_api_server_url'; parent::__construct($para); } } class OrderApi extends MyApiServerApi { function __construct($para) { $this->end_point = '/order'; parent::__construct($para); } public static function fetch_index(array $url_para = []) { return (new self([ 'url_para' => $url_para ]))->exe(); } } $api = OrderApi::fetch_index([ 'url_para' => ['page' => 1, 'page_size' => 24] ]);

Reach result and error handle

if ($api->is_error()) throw new Exception('Somethong go wrong.'); $result = $api->getBody(); // fetch result

Construct - 構成式

method

There are already have multiple default function to help you to set curl method
已經有許多默認函式提供讓你去設置請求 curl 的method

$api = new WLCURL(array $my_construct_para = []); // Default GET method $api = WLCURL::get(array $my_construct_para = []); $api = WLCURL::post(array $my_construct_para = []); $api = WLCURL::put(array $my_construct_para = []); $api = WLCURL::patch(array $my_construct_para = []); $api = WLCURL::delete(array $my_construct_para = []);

Customize method - 客製方法

$api = new WLCURL; $api->method = 'My custom method'; // Same as above $api = new WLCURL(['method' => 'My custom method']); $api = WLCURL::request('My custom method', array $my_construct_para = []);

base_url

As we all knows, URL is the most important foundation of the CURL request. And basic url is the first section of the url
眾所周知, 網址是 curl 請求最重要的一環, 而 basic url 是組成網址的第一個部分

$api = WLCURL::get()->base_url('https://my_api_server_url');

end_point

end_point is the second section of the url, reach your target node
> end_point 是組成網址的第二個部分, 觸及你的目標節點

$api = WLCURL::get()->end_point('/order');

If you want to add end point node, put true in second parameter 如果你想要壘加目標節點, 在第二個參數放上 true

$api->end_point('/{id}', true); // Same as $api = WLCURL::get()->end_point('/order/{id}');

url_para

url_para is the third section of the url, pass your requirement parameter to api server
> url_para 是組成網址的第三個部分, 傳送你所需的參數給目標 api 伺服器

$api = WLCURL::get() ->url_para('page', 1); ->url_para('page_size', 24); // Same as $api = WLCURL::get()->url_para([ 'page' => 1, 'page_size' => 24 ]);

It will generate like '?page=1&page_size=24' string
這會生成像是 '?page=1&page_size=24' 的字串

body

Pass your requirement post field parameter to api server
傳送你所需的 post field 參數給目標 api 伺服器

$api = WLCURL::post() ->body('title', 'My title'); // Add parameter in body structure ->body('content', 'My content'); // Same as $api = WLCURL::post()->body([ // Replace whole body structure 'title' => 'My title', 'content' => 'My content' ]);

header

$api = WLCURL::get()->header('Cache-Control', 'no-cache'); // Add parameter // Same as $api = WLCURL::get()->header(['Cache-Control' => 'no-cache']); // Add parameter // Same as $api = WLCURL::get()->opt(CURLOPT_HTTPHEADER, ["Cache-Control: no-cache"]); // Replace whole curl header structure

It will build header structure like ["Cache-Control: no-cache"]

token

$api = WLCURL::get()->token('My token');

token_type

It will put token_type value in front of token as soon as build token. Defualt value is "Bearer"
在組建 token 參數時, 會將token_type值擺在前面

$api = WLCURL::get()->token_type('Bearer');


If you want to set token manually
如果你想手動設置 token

$api = WLCURL::get()->header('Authorization', 'My token type' . 'My token');

para_type

It will effect the body parameter formation as soon as build curl request.
The default value is "http".
The value only accept in ["http", "json"].
If value equal "http", WLCURL will format body as build_http_query_para.
If value equal "json", WLCURL will format body as json_encode, and set curl header Content-Type as "application/json" automatically.
此參數會直接影響 curl 請求時body參數轉換的形式
預設值是"http".
參數容許值只在["http", "json"]裡面.
如果參數設為"http", WLCURL 會將 body參數設為 build_http_query_para.
如果參數設為"json", WLCURL 會將 body參數設為 json_encode, 並且會自動將 curl header Content-Type 參數設為 "application/json"

$api = WLCURL::get()->para_type('json'); //->header('Content-Type', 'application/json'); If value is "json", WLCURL will set this automatically

opt

Set PHP original curl opt parameter, you can find referance in PHP CURL setopt
設置 PHP 原生 curl opt 參數, 你可以參照此處PHP CURL setopt

$api = WLCURL::get()->opt(CURLOPT_RETURNTRANSFER, true); // Add parameter // Same as $api = WLCURL::get()->header([CURLOPT_RETURNTRANSFER => true]); // Add parameter // Same as $api = WLCURL::get(); $api->opt = [CURLOPT_HTTPHEADER => true]; // Replace whole curl opt structure, It's dangerous, please becareful.

Execute - 執行

exe

WLCURL will do request task as soon as you call exe() function, and WLCURL will not do anything before you call it.
> WLCURL 會在執行 exe() 函式時執行請求任務. WLCURL 不會在你呼叫此函式前做任何事.

$api = (new WLCURL) // Default GET method ->base_url('https://my_api_server_url'); ->end_point('/order'); ->url_para(['page' => 1, 'page_size' => 24]); ->exe();

Error Handle - 錯誤處理

WLCURL is already prepare multiple function to help you handle your error. It only has meaning after exe()

WLCURL 已經準備好許多函式來幫助你處理錯誤狀況. 這只會在執行 exe() 後有意義

is_error

check curl request result return first section http status code is in 4 or 5
Return type boolean
檢查 curl 請求結果回傳的 http 狀態碼第一字節是否是 45
回傳型態 boolean

$api->is_error();

is_client_error

check curl request result return first section http status code is 4 or not
Return type boolean
檢查 curl 請求結果回傳的 http 狀態碼第一字節是否是 4
回傳型態 boolean

$api->is_client_error();

is_bad_request

check curl request result return http status code is 400 or not
Return type boolean
檢查 curl 請求結果回傳的 http 狀態碼是否是 400
回傳型態 boolean

$api->is_bad_request();

is_unauthorized

check curl request result return http status code is 401 or not
Return type boolean
檢查 curl 請求結果回傳的 http 狀態碼是否是 401
回傳型態 boolean

$api->is_unauthorized();

is_forbidden

check curl request result return http status code is 403 or not
Return type boolean
檢查 curl 請求結果回傳的 http 狀態碼是否是 403
回傳型態 boolean

$api->is_forbidden();

is_method_not_allow

check curl request result return http status code is 405 or not
Return type boolean
檢查 curl 請求結果回傳的 http 狀態碼是否是 405
回傳型態 boolean

$api->is_method_not_allow();

is_server_error

check curl request result return first section http status code is 5 or not
Return type boolean
檢查 curl 請求結果回傳的 http 狀態碼第一字節是否是 5
回傳型態 boolean

$api->is_server_error();

get_Http_code

Retrieve raw http status code 取得原生 http 回傳之狀態碼

$api->get_Http_code(); if ($api->get_Http_code() != 200) echo 'Do something.';

get_error_msg

Retrieve the error msg from php original curl 取得 PHP 原生 curl 請求錯誤的錯誤訊息

$api->get_error_msg();

get_info

Retrieve full request info from PHP original curl 取得所有 PHP 原生 curl 請求的回傳訊息

$api->get_info();

Get Request Result - 取得請求結果

It only has meaning after exe().
只有在呼叫exe()函式後有意義.

getBody

Get raw request result body.
取得原始請求後的 body 結果.

$result = $api->getBody();

getdecodeBody

Get request result body that after json_decode.
取得請求後的 json_decode body 結果.

$result = $api->getdecodeBody(); //Same as $result = json_decode($api->getBody()); //There have three option parameter to config decode result same as php json_decode() $result = $api->getdecodeBody($associative = null, int $depth = 512, int $flags = 0);

You may want to handle error before retrieve body
你也許會想要在取得結果前做錯誤處理

if ($api->is_error()) throw new Exception('Somethong go wrong.'); $result = $api->getBody();

Modelly-Best Advance Practice - 模組化-最佳進階做法

Make your own packaged curl model.
製作屬於你自己的 curl 請求模組類別

File Structure - 檔案結構

Models
|- MyApiServerApi (extends WLCURL)
|- Order
|-- OrderApi (extends MyApiServerApi)
|-- OrderProductApi (extends MyApiServerApi)

MyApiServerApi

Make your own target api server model class.
You can set any solid required curl parameter in this model constructor. And you don't have to do this again.
製作你自己的目標 api 請求模組類別.
你可以設置任何請求前所需的目標參數在構成式裡, 你將不需要再做一次.

namespace AppModels; use WeiLunWLCURL; class MyApiServerApi extends WLCURL { function __construct($para) { $this->base_url('https://my_api_server_url'); $this->token('My Api Server Token.'); $this->para_type('json'); parent::__construct($para); } }

TargetApi

Make your own target end point model class. And package your api function.
製作你自己的目標節點請求 api 模組類別. 並打包函式方便日後使用.

namespace AppModelsOrder; use AppModelsMyApiServerApi; class OrderApi extends MyApiServerApi { function __construct($para) { $this->end_point('/order'); parent::__construct($para); } public static function index(int $page = 1, int $pae_size = 24) { return self::get([ 'url_para' => [ 'page' => $page, 'page_size' => $page_size ] ])->exe(); } public static function retrieve(int $id) { $self = self::get(); $self->end_point("/$id", true); // Make end_point become /order/{id} return $self->exe(); } public static function create(array $body) { return self::post([ 'body' => $body ])->exe(); } public static function update(int $id, array $body) { $self = self::put(); $self->end_point("/$id", true); // Make end_point become /order/{id} $self->body($body); return $self->exe(); } }

You can use TargetApi (OrderApi) like
你可以使用 TargetApi (OrderApi) 就像

use AppModelsOrderOrderApi; $order_index_api = OrderApi::index(1, 24); $order_api = OrderApi::retrieve(1); $order_api = OrderApi::create([ 'customer_name' => 'My customer name', 'total' => 100 ]); $order_update_api = OrderApi::update(1, [ 'customer_name' => 'Changed customer name', 'total' => 10 ])

版权声明:

1、该文章(资料)来源于互联网公开信息,我方只是对该内容做点评,所分享的下载地址为原作者公开地址。
2、网站不提供资料下载,如需下载请到原作者页面进行下载。
3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考学习用!
4、如文档内容存在违规,或者侵犯商业秘密、侵犯著作权等,请点击“违规举报”。