文章同步於blog
那麼今天直接來實作改造Controller
假設我今天需要一個註冊會員的功能
我們需要驗證資料、儲存資料、金流和物流以及回傳資料
今天我會先用DI(依賴注入)的方式來撰寫,這個下次有機會再來介紹
class MemberController extends Controller
{
protected $member_validator;
protected $member_use_case;
protected $member_repository;
protected $member_formatter;
public __construct(MemberValidator $member_validator, MemberUseCase $member_use_case, MemberRepository $member_repository, MemberFormatter $member_formatter)
{
$this->member_validator = $member_validator;
$this->member_use_case = $member_use_case;
$this->member_repository = $member_repository;
$this->member_formatter = $member_formatter;
}
public function registerMember(Request $request)
{
$request_data = $request->data;
// 驗證請求參數
$error_key_group = $this->member_validator->getRegisterMemberErrorKeyGroup($request->data);
if (count(error_key_group) != 0) {
$validate_fail_response_data = $this->$member_formatter->getValidateFailResponseData($error_key_group)
return response()->json($validate_fail_response_data, 400)
}
// 金流和物流
if (!$this->member_use_case->isPaySuccessful($request_data)) {
$pay_fail_response_data = $this->$member_formatter->getPayFailResponseData()
return response()->json($pay_fail_response_data, 400)
}
if (!$this->member_use_case->isGiftSuccessful($request_data)) {
$gift_fail_response_data = $this->$member_formatter->getGiftFailResponseData()
return response()->json($gift_fail_response_data, 400)
}
// 建立資料
try {
$this->member_repository->createMember($request_data);
} catch (\Exception $e) {
$create_data_fail_response_data = $this->$member_formatter->getCreateDataFailResponseData();
return response()->json($create_data_fail_response_data, 400);
}
$success_response_data = $this->$member_formatter->getSuccessResponseData();
return response()->json($success_response_data, 201);
}
}
我們可以得知這個順序是
搭配圖大概長這樣
這樣我們就可以分別為每一層撰寫單元測試,明天我們再來談這一部分