php控制器与服务层的核心区别在于职责分工:控制器负责处理http请求、参数校验和响应返回,而服务层封装具体的业务逻辑和数据操作。在实现上,通常通过依赖注入将服务实例引入控制器,由控制器调用服务方法完成核心计算或数据持久化,从而保持代码的单一职责和高可测试性。

Controller如何接收请求并委托给Service
控制器通过构造函数注入服务实例,并在动作方法中调用服务的具体业务方法。这种设计使得控制器仅关注路由映射和输入输出,而不包含复杂的业务判断逻辑。

// src/Controller/UserController.php
namespace App\Controller;
use App\Service\UserService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class UserController
{
private UserService $userService;
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
public function create(Request $request): Response
{
$data = json_decode($request->getContent(), true);
// 简单的参数校验
if (empty($data['email'])) {
return new Response('Email is required', 400);
}
// 委托给服务层处理核心逻辑
$user = $this->userService->createUser($data);
return new Response(json_encode(['id' => $user->getId()]), 201);
}
}
// src/Service/UserService.php
namespace App\Service;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
class UserService
{
private EntityManagerInterface $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function createUser(array $data): User
{
$user = new User();
$user->setEmail($data['email']);
$user->setPassword(password_hash($data['password'], PASSWORD_BCRYPT));
$this->em->persist($user);
$this->em->flush();
return $user;
}
}
预期结果:当POST请求发送包含email和password的JSON数据时,控制器验证非空后调用createUser,数据库插入新记录并返回用户ID。若缺少email,直接返回400错误,不进入服务层。
立即学习“PHP免费学习笔记(深入)”;
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
Service如何处理事务与异常以保证数据一致性
服务层利用数据库事务机制确保复杂业务操作的原子性,并在发生错误时回滚状态。控制器无需关心底层的数据一致性细节,只需捕获服务层抛出的特定异常并转换为HTTP响应。

// src/Service/OrderService.php
namespace App\Service;
use App\Repository\OrderRepository;
use App\Repository\ProductRepository;
use Doctrine\DBAL\Exception\TransactionRolledBack;
class OrderService
{
private OrderRepository $orderRepo;
private ProductRepository $productRepo;
public function __construct(
OrderRepository $orderRepo,
ProductRepository $productRepo
) {
$this->orderRepo = $orderRepo;
$this->productRepo = $productRepo;
}
public function placeOrder(int $userId, int $productId, int $quantity): void
{
$conn = $this->orderRepo->getConnection();
try {
$conn->beginTransaction();
$product = $this->productRepo->find($productId);
if (!$product || $product->getStock() < $quantity) {
throw new \RuntimeException('Insufficient stock');
}
$product->decreaseStock($quantity);
$this->productRepo->save($product);
$order = new Order();
$order->setUser($userId);
$order->setProduct($product);
$order->setQuantity($quantity);
$this->orderRepo->save($order);
$conn->commit();
} catch (\Throwable $e) {
$conn->rollBack();
throw $e;
}
}
}
预期结果:当库存充足时,扣减库存并创建订单,事务提交成功;当库存不足或数据库写入失败时,触发异常,事务回滚,库存数量保持不变。控制器应捕获RuntimeException并返回500或422状态码。
当Service抛出未捕获异常时控制器的行为表现
如果服务层抛出的异常未在控制器中被显式捕获,框架的全局异常处理器会接管,通常返回500 Internal Server Error或默认的JSON错误响应。开发者应在控制器中针对已知业务异常进行捕获,以提供更有意义的错误信息。


















