eugene-khorev / yii2-json-rpc-controller
Yii2 JSON RPC 2.0 扩展
dev-master
2016-11-27 19:08 UTC
Requires
- yiisoft/yii2: *
This package is not auto-updated.
Last update: 2024-09-25 15:12:29 UTC
README
在配置中更改你的请求组件类为 \jsonrpc\Request
'components' => [ ... 'request' => [ 'class' => 'jsonrpc\Request', 'cookieValidationKey' => '...', ], ... ]
创建一个扩展 \jsonrpc\Controller
的新控制器
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]]; } }
现在,如果你将此 JSON-RPC 2.0 请求发送到 /some/rpc
{ "jsonrpc": "2.0", "method": "echo", "params": { "param1": "abc", "param2": "123" }, "id": 1 }
你将得到以下结果
{ "jsonrpc": "2.0", "id": 1, "result": { "recievedData": { "param1": "abc", "param2": "123" } } }
如果你在浏览器中导航到 /some/index
,你将得到常规的 \Yii2\web\Controller
行为。
高级使用
参数、模型和验证
创建一个新模型
class SomeModel extends yii\base\Model { public $value1; public $value2; }
修改你的 RPC 控制器动作,使其看起来像这样
public function rpcEcho($param1, SomeModel $modelParam) { return ['recievedData' => [ 'param1' => $param1, 'modelParam' => $modelParam->attributes ]]; }
现在,如果你将此 JSON-RPC 2.0 请求发送到 /some/rpc
{ "jsonrpc": "2.0", "params": { "param1": "abc", "modelParam": { "value1": "123", "value2": "321", } }, "id": 1 }
你将在方法中获得有效的 $modelParam
模型。库使用 rpc
或 default
场景来验证参数模型。如果验证失败,客户端将收到包含验证错误的正确 JSON-RPC 2.0 答案,但你的 RPC 动作方法甚至不会运行。
批量请求
您还可以使用批量 JSON-RPC 2.0 请求
[ { "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 } ]
在这种情况下,两个控制器方法 rpcSomeMethod()
和 rpcAnotherMethod()
将按顺序调用。即使其中一个方法出错,客户端也将收到正确的批量结果。