定制 eugene-khorev/yii2-json-rpc-controller 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

eugene-khorev/yii2-json-rpc-controller

Composer 安装命令:

composer require eugene-khorev/yii2-json-rpc-controller

包简介

Yii2 JSON RPC 2.0 extension

README 文档

README

Change your request component class in configuration to \jsonrpc\Request:

   'components' => [
		...
        'request' => [
            'class' => 'jsonrpc\Request',
            'cookieValidationKey' => '...',
        ],
		...
	]

Create a new controller that extends \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]];
	}
}

Now if you post this JSON-RPC 2.0 request to /some/rpc:

{
	"jsonrpc": "2.0", 
	"method": "echo", 
	"params": { 
		"param1": "abc",
		"param2": "123"
	},
	"id": 1
}

You get the following result

{
	"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.

Advanced usage

Parameters, models and validation

Create a new model:

class SomeModel extends yii\base\Model
{
	public $value1;
	public $value2;
}

Make changes to you RPC controller action so it looks like this:

	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:

{
	"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.

Batch requests

You can also use batch JSON-RPC 2.0 requests:

[
	{
		"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.

统计信息

  • 总下载量: 180
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 3
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 3
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2015-02-23

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固