如果我們有很多個模組API要管理的話,我會在\app\Services\這底下建立不同的模組service,分別管理不同模組要call的API,像是我們iscar專案有很多個模組(ex:member、pm、brand、app、temple...等等),所以就會有不同的service來管理我要去那個模組call API的function。
<?php
namespace App\Services;
define('QueryMember', config('global.query_member'));
define('ModifyMember', config('global.modify_member'));
define('Modacc', config('global.modacc'));
define('Modvrf', config('global.modvrf'));
class MemberService {
/**
* call member模組的API [QueryMember]
* @param [type] $md_mobile [會員手機號碼]
* @param [type] $md_contactmail [會員電子信箱]
* @global route QueryMember [member模組的API]
* @global string Modacc [模組帳號]
* @global string Modvrf [模組驗證碼]
*/
public function callApiQueryMember($md_mobile,$md_contactmail){
// 編輯要call API所需要傳入的值
$arraydata['md_mobile'] = $md_mobile;
$arraydata['md_contactmail'] = $md_contactmail;
$arraydata['modacc'] = Modacc;
$arraydata['modvrf'] = Modvrf;
$url = QueryMember;
// call API
$request = \App\Library\CommonTools::curlModule($arraydata,$url);
$request = $request['query_memberresult'];
return $request;
}
/**
* call member模組的API [ModifyMember]
* @param [type] $md_id [會員代號]
* @param [type] $md_clienttype [會員類型]
* @global route ModifyMember [member模組的API]
* @global string Modacc [模組帳號]
* @global string Modvrf [模組驗證碼]
*/
public function callApiModifyMember($md_id,$md_clienttype){
// 編輯要call API所需要傳入的值
$arraydata['md_id'] = $md_id;
$arraydata['md_clienttype'] = $md_clienttype;
$arraydata['modacc'] = Modacc;
$arraydata['modvrf'] = Modvrf;
$url = ModifyMember;
// call API
$request = \App\Library\CommonTools::curlModule($arraydata,$url);
$request = $request['modify_memberresult'];
return $request;
}
}
/**
* Curl模組化使用
* @param type array $post 傳送資料
* @param type string $route 傳送route
* @return array or null
*/
public static function curlModule ($post, $route){
try {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $route,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode(json_encode($post)),
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/json",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
throw new \Exception($err);
} else {
// 將得到的回應(json字串)轉成陣列
return \App\library\CommonTools::ConvertStringToArray($response);
}
} catch(\Exception $ex) {
CommonTools::writeErrorLogByException($ex);
return false;
}
}