Back to results for “Architecture”
PHP › MVC Architecture in PHP

How does the concept of a Service Layer complement traditional MVC by providing an additional place for complex business logic that spans multiple models?

Advanced

Answer

A Service Layer introduces dedicated service classes that sit between controllers and models, handling complex business operations that might involve coordinating multiple models together, external API calls, or transactional logic, which helps prevent controllers from becoming overloaded with orchestration logic while also keeping individual models focused on their own specific data and behavior, rather than each model needing to know about and coordinate with several other unrelated models directly.
class OrderService {
    public function createOrder(array $data): Order {
        DB::transaction(function () use ($data, &$order) {
            $order = Order::create($data);
            $this->inventoryService->reserveStock($order);
            $this->paymentService->charge($order);
        });
        return $order;
    }
}
Real-world example An e commerce application introduces a dedicated OrderService that coordinates between the Order, Inventory, and Payment concerns during checkout, keeping this complex multi step orchestration logic out of both the controller and any single model.

Common follow-ups: How do you decide when a piece of logic warrants moving into a dedicated service class versus staying on the model?;How does this Service Layer pattern relate to the Repository pattern discussed elsewhere?