首页 > 解决方案 > 使用返回实例的方法是反模式吗?

问题描述

在 b4 中很抱歉创建了这样一个模糊的话题,但我会尽量简洁。我正在尝试改进我制作的 php 包的面向对象设计。我有一个代表 en Http 外部 API 的Api类。该类具有getpostdelete等方法,并封装了一些响应检索或 json 解码。这个类接收一个 GuzzleHttp 客户端,因为它是这样做的构造函数参数。

然后,我为 API 具有的许多端点类别创建了一些类,例如SaleUser等......您可以在Sale之类的类中找到一个示例方法recent(),它的代码将执行以下 操作$this->api->get('recent-sales-endpoint.json'):这需要将API作为依赖项注入到Sale中,这样我就可以编写它的单元测试,就像我一直做的那样。

现在,如果我尝试充当安装了我的库并想要获得最近的销售的用户,我必须执行以下操作:

$api = new Api($client);
$sale = new Sale($api);
$recentSales = $sale->recent();
$car = new Car($api);
$newCars = $car->getNew();

所以我想知道这是一种改进还是一种反模式,可以让我的包更易于使用。

在我的API类构造函数中,我为每个类别类创建实例,例如。

private $client;
private $car;
private $sale;
public function __construct(Client $client)
{
    $this->client = $client;
    $this->car = new Car($this);
    $this->sale = new Sale($this);
}

然后我可以创建访问方法,例如:

public function sale()
{
    return $this->sale
}

因此,对于包用户现在要检索数据,它将是:

$api = new Api($client);
$recentSales = $api->sale()->recent();
$newCars = $api->car()->getNew();

你认为这两种方式中哪一种是最正确的方式?另外我认为我可以在第一次查询时初始化这些实例,而不是在构造函数中进行,但我不知道我是否使设计过于复杂。

标签: phpoopdesign-patterns

解决方案


我认为这样做没有正确和不正确的方法。我觉得您的选项 2 使用起来感觉很好:

$api = new Api($client);
$recentSales = $api->sale()->recent();

您希望包的 API 看起来如何,这取决于您。我认为让它有点灵活是个好主意,这样使用你的包的开发人员可以选择最适合他们的用例的选项。

你总是可以看看其他包是怎么做的,我喜欢这个来自 stripe 的库: https ://github.com/stripe/stripe-php/tree/master/lib

https://github.com/stripe/stripe-php


推荐阅读