紀錄工作經驗、相關知識,解決技術相關問題。

MySQL, PHP

Fat Controller 重構:MVC 架構中拆分 Service Layer 與 Repository Pattern 實務

Fat Controller 重構:MVC 架構中拆分 Service Layer 與 Repository Pattern 實務 特色圖片

在 Web 應用程式開發初期,MVC 模式(Model-View-Controller)憑藉著直覺的職責切分,成為多數框架的核心基石。Fat Controller 重構要處理的,就是隨業務規模擴張而膨脹的 Controller。

這類 Controller 會承擔 HTTP 請求解析、資料驗證、業務邏輯計算、外部 API 呼叫以及資料庫 Transaction 管理等龐雜任務,在軟體工程中被稱為 Fat Controller。程式碼可讀性因此下滑,單元測試也變得難以進行。

想了解基礎軟體測試環境的區別,可前往 〈SIT , UAT 是什麼 ? 簡單說明 SIT測試與UAT測試〉 觀看。本文以 Laravel 為例,解析 Fat Controller 的維護隱患,並提供導入 Service Layer 與 Repository Pattern 的標準重構解法。

一、 核心速查與常見瓶頸對照

面對日益龐大的控制器,盲目拆分往往會造成檔案過多卻毫無結構的混亂局面。以下先釐清常見的錯誤寫法與核心架構的職責對照。

1. 常見錯誤寫法的工程瓶頸

  • 業務邏輯與 HTTP 請求緊密耦合:Controller 直接處理 Request 參數並操作資料庫,導致相同的商業邏輯無法被 Console Command 或排程任務(Cron Job)複用。
  • 單元測試困難度高:因為 Controller 同時依賴框架的 HTTP Context 與資料庫實體,編寫自動化測試時必須模擬龐大的框架環境。
  • 違反單一職責原則(SRP):當需求變更時,開發者頻繁修改同一個 Controller 檔案,大幅增加 Git Conflict(版本衝突)的發生機率。

2. 核心機制規格對照表

層級名稱主要職責允許依賴項目嚴禁包含項目
Controller接收 HTTP 請求、呼叫服務層、回傳 ResponseService Layer、Request Validations直接寫入 SQL 查詢、複雜商業運算
Service Layer封裝核心業務邏輯、協調多個資料源與交易Repository、外部 API ClientHTTP Status Code、Request 參數解析
Repository抽離資料存取細節、組合 SQL 查詢語法ORM、Database Connection商業邏輯判斷、Session 狀態處理

二、 關鍵機制解析:底層規範與注意事項

在著手進行重構前,必須先理解各個分層之間的依賴方向(Dependency Direction)。在現代架構設計中,依賴關係應該單向流動:由 Controller 指向 Service,再由 Service 指向 Repository。

1. 職責劃分與依賴注入(Dependency Injection)

透過依賴注入(Dependency Injection),Service 與 Repository 可以透過介面(Interface)或容器注入到 Controller 中。這不僅能解開硬編碼(Hard-coding)的緊密耦合,更能在撰寫單元測試時輕鬆替換成 Mock 物件。

以 Laravel 為例,服務容器會自動解析建構子型別提示的具體類別,不需額外設定。若型別提示的是介面,就必須在 Service Provider 中告訴容器該介面對應哪個實作,後文範本三會示範。

補充說明:Service Layer 與 Repository 的定義以 Martin Fowler《Patterns of Enterprise Application Architecture》的目錄頁為準。Repository 在領域層與資料對應層之間,以類似集合的介面存取領域物件;Service Layer 定義應用程式邊界與可用操作,並協調每個操作的回應。

2. Transaction 資料庫異動交易的管理邊界

當商業邏輯牽涉多張資料表的寫入(例如電商系統扣除庫存、建立訂單、扣款)時,Transaction 必須在 Service Layer 中宣告與管理,而非分散在 Controller 或底層的 Repository 中。這確保了當任一步驟失敗時,整個異動能夠完整復原(Rollback)。Martin Fowler 對 Service Layer 的描述也包含由它控制交易。


三、 實作範本:生產環境完整程式碼

以下提供重構前後的程式碼對比,展示如何將原本臃腫的控制器拆分為高內聚、低耦合的服務層架構。

範本一:重構前的 Fat Controller 樣貌

// 重構前:集中所有邏輯於 Controller 的不良示範
class OrderController extends Controller {
    public function store(Request $request) {
        // 1. 驗證請求
        $validated = $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
        ]);

        // 2. 直接操作資料庫與複雜邏輯計算
        DB::beginTransaction();
        try {
            $product = Product::find($validated['product_id']);
            if ($product->stock < $validated['quantity']) {
                throw new \Exception('庫存不足');
            }

            $product->stock -= $validated['quantity'];
            $product->save();

            $order = Order::create([
                'user_id' => auth()->id(),
                'product_id' => $product->id,
                'quantity' => $validated['quantity'],
                'total_price' => $product->price * $validated['quantity']
            ]);

            DB::commit();
            return response()->json(['status' => 'success', 'data' => $order]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['status' => 'error', 'message' => $e->getMessage()], 400);
        }
    }
}

範本二:引入 Service Layer 與 Repository 後的乾淨架構

// 重構後:Controller 僅負責收送 HTTP 請求
class OrderController extends Controller {
    protected $orderService;

    public function __construct(OrderService $orderService) {
        $this->orderService = $orderService;
    }

    public function store(StoreOrderRequest $request) {
        try {
            $order = $this->orderService->createOrder(
                auth()->id(),
                $request->validated()
            );
            return response()->json(['status' => 'success', 'data' => $order]);
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => $e->getMessage()], 400);
        }
    }
}

// 業務邏輯封裝於 Service Layer
class OrderService {
    protected $orderRepo;
    protected $productRepo;

    public function __construct(OrderRepositoryInterface $orderRepo, ProductRepositoryInterface $productRepo) {
        $this->orderRepo = $orderRepo;
        $this->productRepo = $productRepo;
    }

    public function createOrder(int $userId, array $data) {
        return DB::transaction(function () use ($userId, $data) {
            $product = $this->productRepo->findByIdForUpdate($data['product_id']);
            
            if ($product->stock < $data['quantity']) {
                throw new \Exception('庫存不足');
            }

            $this->productRepo->decrementStock($product->id, $data['quantity']);

            return $this->orderRepo->create([
                'user_id' => $userId,
                'product_id' => $product->id,
                'quantity' => $data['quantity'],
                'total_price' => $product->price * $data['quantity']
            ]);
        });
    }
}

範本三:Repository 介面、實作與服務容器綁定

範本二的 OrderService 在建構子型別提示的是介面,所以要先定義介面與實作,再於 Service Provider 綁定。

  1. 定義 Repository 介面。
// app/Repositories/ProductRepositoryInterface.php
interface ProductRepositoryInterface {
    public function findByIdForUpdate(int $id): object;
    public function decrementStock(int $id, int $quantity): void;
}

// app/Repositories/OrderRepositoryInterface.php
interface OrderRepositoryInterface {
    public function create(array $attributes): Order;
}
  1. 撰寫實作。悲觀鎖 lockForUpdate() 建議包在交易內使用,範本二已由 Service 的 DB::transaction() 包住。
// app/Repositories/EloquentProductRepository.php
class EloquentProductRepository implements ProductRepositoryInterface {
    public function findByIdForUpdate(int $id): object {
        $product = DB::table('products')->lockForUpdate()->find($id);

        if ($product === null) {
            throw new \RuntimeException('商品不存在');
        }

        return $product;
    }

    public function decrementStock(int $id, int $quantity): void {
        DB::table('products')->where('id', $id)->decrement('stock', $quantity);
    }
}

// app/Repositories/EloquentOrderRepository.php
class EloquentOrderRepository implements OrderRepositoryInterface {
    public function create(array $attributes): Order {
        return Order::create($attributes);
    }
}
  1. 在 AppServiceProvider 的 register 方法中,把介面綁定到實作。
// app/Providers/AppServiceProvider.php
public function register(): void
{
    $this->app->bind(OrderRepositoryInterface::class, EloquentOrderRepository::class);
    $this->app->bind(ProductRepositoryInterface::class, EloquentProductRepository::class);
}

補充說明:Order::create() 需要先在 Order 模型指定可大量賦值的欄位(Laravel 文件稱為 Fillable 或 Guarded),否則會因大量賦值保護而無法寫入。


四、 常見問題與排錯(Q&A)

Q1:如何識別專案中的 Controller 已經陷入 Fat Controller 的程式碼壞味道?

  • 問題原因:當 Controller 同時引入大量外部依賴(Model、Service、Helper 等),且包含大量 if-else 商業判斷與 SQL 查詢時,即代表陷入壞味道。行數與依賴數量沒有通用的官方門檻,以職責是否超出 HTTP 層為判斷依據。
  • 解法:應立即檢視其職責,將資料存取抽離至 Repository,並把非 HTTP 導向的計算邏輯搬移至 Service Layer。

Q2:將複雜的業務邏輯從 Controller 轉移至 Service Layer 時,應遵守哪些職責劃分原則?

  • 問題原因:開發者常誤將所有程式碼隨意塞入 Service,導致 Service 本身變成另一個肥胖物件。
  • 解法:Service Layer 應專注於「協調商業流程」。若某段邏輯屬於單一實體的純資料驗證或狀態轉換,應下放至 Model 或專屬的 Domain Object 中。

Q3:當 Controller 需要同時呼叫多個資料庫實體時,如何運用 Repository Pattern 抽離資料存取?

  • 問題原因:直接在 Controller 中呼叫多個 Model 會導致程式碼高度耦合框架的 ORM。
  • 解法:透過定義介面(Interface),讓 Service 透過建構子注入多個專屬的 Repository(例如 UserRepository、ProductRepository),由 Repository 內部封裝複雜的 Eloquent 或 Query Builder 查詢。

Q4:重構後的 Service Layer 該如何妥善處理 Transaction 資料庫異動交易?

  • 問題原因:將資料庫交易寫死在 Controller 中會破壞架構純淨度。
  • 解法:利用框架提供的閉包交易機制(如 DB::transaction())包覆 Service 內部的方法呼叫。閉包內丟出例外時,Laravel 會自動 rollback 並重新丟出例外;閉包成功執行則自動 commit,跨多個 Repository 的寫入因此同進同退。

Q5:導入 Service Layer 後,對於後續編寫單元測試與 Mock 物件帶來什麼實質幫助?

  • 問題原因:測試 Controller 需要模擬 HTTP Session、Cookie 與路由 Middleware,門檻極高。
  • 解法:由於業務邏輯已獨立至 Service,單元測試可以直接對 Service 進行隔離測試,並透過 Mock 掉 Repository 依賴,大幅提升測試執行速度與穩定度。

Q6:在進行重構時,如何確保既有的系統整合測試與使用者驗收測試流程不被破壞?

  • 問題原因:大規模重構容易引入未預期的行為變更。
  • 解法:在重構前確保專案具備覆蓋率足夠的自動化測試案例,並採用漸進式重構,一次抽離一個 API 端點的邏輯,每一步都執行測試驗證。

Q7:建構胖控制器重構計畫時,如何避免過度設計造成程式碼過度破碎?

  • 問題原因:盲目為每個簡單的 CRUD 操作建立專屬的 Service 與 Repository 類別,導致專案充斥大量只有一行程式碼的轉發檔案。
  • 解法:針對簡單且不帶複雜商業邏輯的單純資料讀寫,允許直接透過 Model 處理,僅針對具備多步驟、外部 API 互動或複雜商業計算的流程導入 Service Layer。

參考資料與延伸閱讀

發佈留言