【发布时间】:2024-10-11 07:50:02
【问题描述】:
我将从头开始为 REST API 创建一个 PHP 客户端。我考虑使用Guzzle library。
我认为用户不应该处理请求对象之类的传输(即使来自自定义 xxxRequest 类),而应该只处理业务对象/服务类。但也许我错了……
以下是一些可能的架构示例。哪些方面尊重良好做法,为什么?
随意改进它们或提出更好的方法。
示例 1:
class ApiClient {
function createBooking (BookingEntity $booking, CustomerEntity $customer) {
//...
}
}
此示例允许用户仅使用业务对象,但如果 API 需要大量方法,则 ApiClient 类可能会开始变脏...此外,如果我们要添加功能,则必须修改 ApiClient。
示例 2:
class ApiClient {
function execute(CreateBookingRequest $createBookingRequest) {
//...
}
}
class CreateBookingRequest {
private BookingEntity $booking;
private CustomerEntity $customer;
private $queryParams;
public createQueryParams() {
// to create the query params (from the attibutes) for the http client
}
}
这里如果需要一个新特性,ApiClient 不需要修改,只需要创建一个新类。但是,用户必须处理以 Request 后缀命名的类。 IMO 他对请求或技术问题一无所知。
示例 3:
class BookingService {
function createBooking (BookingEntity $booking, CustomerEntity $customer) {
//...
}
}
这个例子添加了一层。
在所有情况下,ApiClient/Service 类中的 Guzzle httpClient 属性应该在哪里?还是应该 ApiClient 类扩展 Guzzle Client 类?
【问题讨论】:
标签: web-services guzzle api-design