第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

PHP
Qyouu 2023-07-08 15:44:54
使用 Laravel 7.*,我的任務(wù)是創(chuàng)建一個簡單的應(yīng)用程序來發(fā)送付款請求,用戶填寫表單并發(fā)送數(shù)據(jù),然后驗證用戶輸入并創(chuàng)建一個新的 Payment 實例。然后用戶被重定向回同一頁面。(當(dāng)然還有其他要求列出所有付款并更新付款):   //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();        }    }一切都很好,但我需要實現(xiàn)一個 Restful API 來執(zhí)行相同的請求并獲得有效的 json 響應(yīng),假設(shè)沒有前端 JavaScript 框架,實現(xiàn)此目標的最佳方法是什么?我應(yīng)該創(chuàng)建一個單獨的控制器嗎?或者簡單地檢查請求是從傳統(tǒng)表單還是API客戶端發(fā)送的?我錯過了設(shè)計模式嗎?
查看完整描述

2 回答

?
慕森卡

TA貢獻1806條經(jīng)驗 獲得超8個贊

最簡單的方法是檢查您應(yīng)該發(fā)回什么樣的響應(yīng):


   //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您當(dāng)然可以選擇將其封裝在實現(xiàn)該接口的類中


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);

        }

    }

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


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

TA貢獻1906條經(jīng)驗 獲得超3個贊

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


通過利用此模式,您可以在應(yīng)用程序的不同區(qū)域重復(fù)使用您的服務(wù)。例如,您可以擁有一個專門用于服務(wù)傳統(tǒng) Web 應(yīng)用程序的控制器,以及一個通過返回 JSON 數(shù)據(jù)來服務(wù) SPA 的控制器,但服務(wù)相同的業(yè)務(wù)流程。


例如:


付款回復(fù):


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;

    }

}

付款服務(wù):


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());

}

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


您可以探索不同的架構(gòu),例如 Clean Architecture + DDD。它將使您的開發(fā)體驗更好,通過依賴抽象實現(xiàn)領(lǐng)域邏輯的集中化和層與層之間的低耦合。


查看完整回答
反對 回復(fù) 2023-07-08
  • 2 回答
  • 0 關(guān)注
  • 153 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號