For me, the data I want to retrieve may be in database for which I can use properties of model and also relationships, but if the record is not a property and no relationship exists for that particular record, I need to check it from an API end point, so where I should place my API request code, is it okay to put the code in model and when retrieving I will retrieve either from database or API depending on situation?

Note: API will not update or insert data in my database.

有帮助吗?

解决方案

In my opinion, you should add another abstract layer (for example, a repository) between the model and the client using it. I think it's better if we keep the model clean from infrastructure related code (quering database, calling API, ...). The following is my pseudo code, not in any specific language.

The repository interface

interface ModelRepositoryInterface {
    public Model getModelById(int id);
}

Start with a database repository:

class DatabaseModelRepository implement ModelRepositoryInterface {
    public Model getModelById(int id) {
        // query from database
    }
}

Then add the API decorator over it:

class ApiDecoratedModelRepository implement ModelRepositoryInterface {
    private ModelRepositoryInterface baseRepository;

    constructor(ModelRepositoryInterface base) {
         this.baseRepository = base;
    }

    public Model getModelById(int id) {
         Model dbModel = this.baseRepository.getModelById(id)
         if (dbModel is not null) then return dbModel;
         return this.getModelFromApi(id);
    }
}

Your client should contains the reference to an instance of the API decorated repository when it want to retrieve a model instance. Dependency Injection is highly recommended to make the process of initialising repositories easier.

许可以下: CC-BY-SA归因
scroll top