use REST API as model source

Hi,

in my case, my Yii2 application should not provide an REST API, but it have to act as an REST API client in order to read an write data to an REST service on an different host.

So my question: what is the best practice, to put the code for loading data from an REST Web Service? Is the controller the right place?

Or isn’t the model the place for dealing with data?

Is it possible to connect an model with an remote REST API as data source (out of the box) instead of linking an model to an database (which works out of the box in yii)?

How would you handle this needs?

Thank you.

Borner

No.

You can extend Model (not ActiveRecord class):

http://www.yiiframework.com/doc-2.0/yii-base-model.html

and use rules for validation.

But Model class has no find() and save() methods. You should code them (or other required) methods.

Thank you.

If I have my own model, which takes the data from an rest api.

Is there a way to create an AR object from that model? Because there are some interesting Yii features I like to use, but those features need an AR.

What exactly features of ActiveRecord do you want to use?

I have been thinking about the question for a quite time… I have got a general idea on that subject. It could be done like it has been done for MongoDB which keeps the data as JSON structure. Maybe it is possible to get some ways to operate on that structures out and build something to cover the basic methods to operate on JSON. Or, finding a library written in PHP to operate on JSON which is already done & well tested and cover it within AR interface.

Or write just a wrapper for http://www.yiiframework.com/doc-2.0/yii-helpers-arrayhelper.html :slight_smile:

Just general idea to keep the subject up.

Hey, I was digging through the github repos and have found https://github.com/yii2tech/filedb. I think you could take a closer look at this because it may be the thing (or very close to it) what you are looking for!

your model would just extend model not activerecord. You can do everything that you can do in AR except the db query stuff which isn’t needed since you’re using an external api.

Your searchModel would use arraydataprovider instead of activedataprovider. The allModels would be the result of the api call. you can do everything you normally could if the data was coming from yii.

The save(), find(), etc. are not needed as api’s use get, put, post, delete etc as the methods. You can define these in your controller and use the HttpClient module that Yii has to send and receive this data.