lundi 7 septembre 2015

How to use specific instances of a resource when using static methods (PHP)

I've been tasked with developing a website (PHP) where most of its content is derived from a private web API (JSON). This has been a steep learning curve for me in terms of application design but so far I have:

  1. Created a PHP SDK/wrapper library to provide me with methods for fetching and saving the data to and from the API. I've looked to examples such as the Google Client SDK for inspiration. Internally it uses GuzzleHttp to do the heavy lifting.

  2. Created a model class for each of the data responses I expect from the API. Now I can work with actual class models with predictable and pre-defined variables.

  3. Used the excellent JSONMapper package to recursively map my API JSON responses into model instances.

Now to the question.

I thought it would be a good idea to provide methods on each model such as:

$user->save()

This would save the instantiated object's data using the API SDK instance available within the model. The application doesn't need to care about where the data store is, or how to use the API. All good.

I therefore also thought it a good idea that the objects should be able to fetch themselves (like how Laravel does, with its Foo::find() pattern), so I created static methods such as:

$user = User::get_by_id(1);

The problem is, as this is a static method, I do not have a way of accessing a specific instance of my API SDK from within the User model. I have no way of injecting that dependency.

As "User" extends "Model" in this example, I therefore used:

Model::$api = new Api;

This is great for now, but if for any reason I need to use a specific instance of my API SDK on certain models, I won't be able to.

How best can I use a specific instance of my API SDK while still providing these static methods on my objects, or am I barking up the wrong tree and this is an anti-pattern and I should instead be using some other mechanism for creating and fetching objects?

I am currently working through "PHP, Objects Patterns and Practice" because I'm struggling with this stuff.

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire