How to use a RESTful API as ORM in CakePHP 3?

2020-02-11 09:30发布

问题:

In CakePHP 1.x/2.x, it was fairly simple to have a model's data come from a REST API (as opposed to a relational database), by defining a custom datasource. (Neil Crookes' CakePHP-ReST-DataSource-Plugin was a great place to start.) Slap your custom datasource on your model, and you're making calls like $this->MyModel->find() just like you were querying a MySQL table called my_models.

I'm trying to figure out how to achieve this same effect under CakePHP 3.0. That is, make find()/save()/set()/get() calls against a Table/Entity driven by a REST API.

Since 3.0's ORM system is A) fairly new, and B) a rather large departure from the old way of doing things, I haven't found any information about how to do something like this. In fact, based on this SlideShare from José Lorenzo Rodríguez, it sounds like it might not be possible.

This means:

  • not going to connect to stuff that is not a relational database.

Is there someone more familiar with CakePHP 3.0 that could clarify if what I'm looking for is possible under the new ORM system? If so, could you explain what classes you'd have to extend or implement to achieve such a function?

回答1:

If you want to create a complete adapter for your Rest datasource using the interfaces and classes provided by CakePHP, take a look at this early experiment fro the CakePHP team on making a datasource for Elastic Search.

Elastic Search uses a Rest API and this plugin attempts to create classes that work similar to the CakePHP ORM:

https://github.com/cakephp/elastic-search

What it implements is basically the following:

  • A Type class that implements the RepositoryInterface
  • A Document class that implements the EntityInterface
  • A Query class that can be used as a collection object and has similar methods

In the near future it will provide a paginator adaptor and a form helper adaptor.

If you want to save yourself this trouble, because there for you there is little value in exposing your datasource as something ORM-like, you can just use guzzle or any similar library to interface with your API and use it as a service instead of a full-blown layer.



回答2:

In the year since I asked this question, UseMuffin has built a Webservice plugin that purports to "bring [...] the power of the CakePHP ORM to your favourite webservices." This sounds like exactly what I wanted at the time.