亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel 同時處理來自 API 和表單的請求的最佳策略

Laravel 同時處理來自 API 和表單的請求的最佳策略

PHP
Qyouu 2023-07-08 15:44:54
使用 Laravel 7.*,我的任務是創建一個簡單的應用程序來發送付款請求,用戶填寫表單并發送數據,然后驗證用戶輸入并創建一個新的 Payment 實例。然后用戶被重定向回同一頁面。(當然還有其他要求列出所有付款并更新付款):   //In PaymentController.php   public function store()    {        $inputData = $this->validateRequest();        $person = $this->personRepository->findOneByAttribute('id_number', request('id_number'));        if ($person instanceof Person) {            $this->paymentRepository->create($inputData, $person);            return back()->with('successMessage', 'Your payment request registered successfully.');        } else {            return back()->with('failureMessage', 'Shoot! Cannot find a peron with the given Identification Number.')->withInput();        }    }一切都很好,但我需要實現一個 Restful API 來執行相同的請求并獲得有效的 json 響應,假設沒有前端 JavaScript 框架,實現此目標的最佳方法是什么?我應該創建一個單獨的控制器嗎?或者簡單地檢查請求是從傳統表單還是API客戶端發送的?我錯過了設計模式嗎?
查看完整描述

2 回答

?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

最簡單的方法是檢查您應該發回什么樣的響應:


   //In PaymentController.php


   public function store()

    {

        $inputData = $this->validateRequest();


        $person = $this->personRepository->findOneByAttribute('id_number', request('id_number'));


        if ($person instanceof Person) {

            $this->paymentRepository->create($inputData, $person);

            if (request()->expectsJson()) {

                return response('', 201); // Just a successfully created response 

            }

            return back()->with('successMessage', 'Your payment request registered successfully.');

        } else {

            if (request()->expectsJson()) {

                return response()->json([ 'error' => 'Not found' ], 404); // You can change the error code and message (or remove the message) as needed

            }

            return back()->with('failureMessage', 'Shoot! Cannot find a person with the given Identification Number.')->withInput();

        }

    }

Responsible您當然可以選擇將其封裝在實現該接口的類中


class PaymentResponse implements Responsible {

     private $success;

     public function __construct($success) {

           $this->success = $success;

     }


     public function toResponse($request) {

         if ($this->success) {

            if (request()->expectsJson()) {

                return response()->json([ 'error' => 'Not found' ], 404); // You can change the error code and message (or remove the message) as needed

            }

            return back()->with('failureMessage', 'Shoot! Cannot find a person with the given Identification Number.')->withInput();

          } 

          if (request()->expectsJson()) {

              return response()->json([ 'error' => 'Not found' ], 404); // You can change the error code and message (or remove the message) as needed

          }

          return back()->with('failureMessage', 'Shoot! Cannot find a person with the given Identification Number.')->withInput();

     }

  

}

那么你的代碼將是:


//In PaymentController.php


   public function store()

    {

        $inputData = $this->validateRequest();


        $person = $this->personRepository->findOneByAttribute('id_number', request('id_number'));


        if ($person instanceof Person) {

            $this->paymentRepository->create($inputData, $person);

            return new PaymentResponse(true);

        } else {

            return new PaymentResponse(false);

        }

    }

當然,您也可以將控制器邏輯提取到單獨的庫中,然后擁有兩個單獨的控制器方法,并且如果需要,仍然可以使用負責的對象。這實際上取決于您的用例以及最適合您的方法


查看完整回答
反對 回復 2023-07-08
?
一只名叫tom的貓

TA貢獻1906條經驗 獲得超3個贊

我認為另一種方法是利用服務存儲庫模式。您將應用程序服務包裝在一個單獨的類中。服務是控制器和存儲庫之間的交互器。流程看起來像[request] -> [controller] -> [service] -> [repository]。


通過利用此模式,您可以在應用程序的不同區域重復使用您的服務。例如,您可以擁有一個專門用于服務傳統 Web 應用程序的控制器,以及一個通過返回 JSON 數據來服務 SPA 的控制器,但服務相同的業務流程。


例如:


付款回復:


class PaymentStoreResponse

{

    protected $message;

    protected $code;

    protected $extraData;


    public function __construct($message, $code, $extraData = "")

    {

        $this->message = $message;

        $this->code = $code;

        $this->extraData = $extraData;

    }


    public function getMessage()

    {

        return $this->message;

    }


    public function getCode()

    {

        return $this->code;

    }

    

    public function getExtraData()

    {

        return $this->extraData;

    }

}

付款服務:


function store($data)

{

    $person = $this->personRepository->findOneByAttribute('id_number', $data('id_number'));


    if ($person instanceof Person) {

        $this->paymentRepository->create($inputData, $person);

        return new PaymentResponse("paymentSuccess", 201, "successMessage");

    } else {

        return new PaymentResponse("notFound", 404, "failureMessage");

    }

}

控制器:


// App\Controllers\Web\PaymentController.php

function store(Request $request)

{

    $inputData = $this->validateRequest();

    $response = $this->paymentService->store($inputData);

    

    return back()->with($response->getExtraData(), $response->getMessage()) 

}



// App\Controllers\Api\PaymentController.php

function store(Request $request)

{

    // validation might be different because

    // api might need to authenticate with jwt etc.

    $inputData = $this->validateRequest();

    $response = $this->paymentService->store($inputData);


    return response()->json(['message' => $response->getMessage()], $response->getCode());

}

這將產生一個更干凈的控制器,因為控制器將只處理請求驗證和響應,同時將業務流程委托給服務類(支付服務)。業務邏輯也集中在服務層,這意味著如果業務發生變化,它將應用到API控制器和Web控制器。因此,它將把你從重構噩夢中拯救出來。


您可以探索不同的架構,例如 Clean Architecture + DDD。它將使您的開發體驗更好,通過依賴抽象實現領域邏輯的集中化和層與層之間的低耦合。


查看完整回答
反對 回復 2023-07-08
  • 2 回答
  • 0 關注
  • 179 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號