📜 ⬆️ ⬇️

REST + RPC API based service technology is done in turbo mode

For some reason, we are used to separating REST and RPC, this separation seems artificial to me. Just REST is stricter and limited in methods, and this is not always justified in a complex application.

Let's make a simple basis for writing a service-oriented architecture. As a stack of technologies we use glorious Yii2, fast Nginx and lightning fast Redis. Why so, it will become clear later.

To manage entities at the primitive level of REATE, UPDATE, DELETE, GET, we have enough Rest technology which is incorporated in Yii2.
')
In order to facilitate the work in the Nginx + Redis coupling, we will have to use a slightly non-standard approach, that is, we will fully convey as parameters: class, method, and other necessary parameters. To validate this company, we use the simplest form of the Yii2 Model (to save space, ignore the code style):

class QueryForm extends Model { /** * @properties for REST */ public $restModel = ''; // Class public $restMethod = ''; // Method public $restId = null; // Rest id  public $restAttributes = []; //   /** * @properties for RPC */ public $categories = []; //     public $tags = []; //    public $match = ''; //    public $cache = 1; //   //     ... 

Further, respectively, the validation of all this fun company, then obviously, I hope.

Nginx under certain conditions (if additional modules are needed - the link below) can intercept the link, send a request to Redis, and if Redis doesn’t find anything with a key, then we will raise PHP Yii2, which will prepare a response using the actionCall method and write it to the cache (working on the same Redis).

 $params = $this->getEncodeParams($key); $query = new \common\models\QueryForm(); if ($query->validateParams($params)) { $this->setHeader(self::CODE_OK, self::MSG_OK); $this->setData($this->callDispatcher($query)); } else { $this->setHeader(self::CODE_ERROR, self::MSG_INPUT_PARAMETER_ERROR . print_r($query->getErrors(), true)); } $this->response(); 

Schematically, the callDispatcher dispatcher, which handles REST and RPC:

1) First, the requests by ID: POST, GET, DELETE, CREATE (everything is just thanks to Yii2).

2) Finally, after this, in the dispatcher, we will process requests for all RPC entities needed by your application.

What we have in the end:

- A single class method, actionCall ($ key), that will handle any REST and RPC request.
- keParams is a universal coded key that is suitable for receiving the service response using the Nginx + Redis hitch ( for details here ), bypassing PHP, and at the same time it is suitable for processing a request using PHP FM Yii2.

If it seems to you that it will be inconvenient to work with such links (url), then this is not quite so, a little ingenuity - and everything will be very convenient for you. Some already quite obvious things deliberately omitted.

Good luck, colleagues!

Source: https://habr.com/ru/post/276781/


All Articles