dev-master
9999999-devYii2 JSON RPC 2.0 extension
MIT
The Requires
by Eugene Khorev
extension json yii2 rpc
Yii2 JSON RPC 2.0 extension
Change your request component class in configuration to \jsonrpc\Request
:, (*1)
'components' => [ ... 'request' => [ 'class' => 'jsonrpc\Request', 'cookieValidationKey' => '...', ], ... ]
Create a new controller that extends \jsonrpc\Controller
:, (*2)
class SomeController extends \jsonrpc\Controller { /** * This is regular controller action */ public function actionIndex() { return $this->render('index'); } /** * This is JSON-RPC 2.0 controller action */ public function rpcEcho($param1, $param2) { return ['recievedData' => ['param1' => $param1, 'param1' => $param1]]; } }
Now if you post this JSON-RPC 2.0 request to /some/rpc
:, (*3)
{ "jsonrpc": "2.0", "method": "echo", "params": { "param1": "abc", "param2": "123" }, "id": 1 }
You get the following result, (*4)
{ "jsonrpc": "2.0", "id": 1, "result": { "recievedData": { "param1": "abc", "param2": "123" } } }
And if you navigate your browser to /some/index
you get regular \Yii2\web\Controller
behavoir., (*5)
Create a new model:, (*6)
class SomeModel extends yii\base\Model { public $value1; public $value2; }
Make changes to you RPC controller action so it looks like this:, (*7)
public function rpcEcho($param1, SomeModel $modelParam) { return ['recievedData' => [ 'param1' => $param1, 'modelParam' => $modelParam->attributes ]]; }
Now if you post this JSON-RPC 2.0 request to /some/rpc
:, (*8)
{ "jsonrpc": "2.0", "params": { "param1": "abc", "modelParam": { "value1": "123", "value2": "321", } }, "id": 1 }
You get valid $modelParam
model in your method. The library uses rpc
or default
scenario to validate parameter models.
If validation fails a client recieves correct JSON-RPC 2.0 answer containing validation error, but your RPC action method doesn't even run., (*9)
You can also use batch JSON-RPC 2.0 requests:, (*10)
[ { "jsonrpc": "2.0", "method": "some-method", "params": { "something": "anything"}, "id": 1 }, { "jsonrpc": "2.0", "method": "another-method", "params": { "data": [1, 2, 3, 4] }, "id": 2 } ]
In this case two controller methods rpcSomeMethod()
and rpcAnotherMethod()
will be called sequentially.
And the client will recieve the correct batch results event if there are errors occurred in one of the methods., (*11)
Yii2 JSON RPC 2.0 extension
MIT
extension json yii2 rpc