dimanche 21 juillet 2019

Is using methods that return instances an antipattern?

In b4 sorry for creating such a vage topic but I'll try to be as concise as possible. I'm trying to improve an object oriented design for a php package I made. I have an Api class that represents en Http external API. This class has methods like get, post, delete etc... and encapsulates some response retrieval or json decoding. This class recieves a GuzzleHttp client as it's constructor parameter to do so.

Then I created some classes for the many endpoint categories the API has like Sale, User, etc... An example method you can find in a class like Sale would be recent() and it's code would do something like: $this->api->get('recent-sales-endpoint.json'). This would require injecting API into Sale as a dependency and this way I could write its unit tests and so as I always do.

Now if I try to act as a user that installed my library and wants to get the recent sales, I have to do things like:

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

So I was wondering if this was is an improvement or an antipattern for making my package more pleasant to use.

On my API class constructor I create instances for every category class like.

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

And then I can create acesssor methods like:

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

So for the package user to retrieve the data now it would be:

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

Which of these two ways do you think is the most correct way? Also I thought I could initialize these instances when being queried the first time instead of doing it in the constructor, but I don't know if I'm complicating the design too much.

Aucun commentaire:

Enregistrer un commentaire