webulla/yii2-rest

Yii2 组件,用于 REST API 集成

安装: 30

依赖项: 0

建议者: 0

安全性: 0

星标: 1

关注者: 2

分支: 1

开放问题: 0

类型:yii2-extension

dev-master 2015-04-18 08:39 UTC

This package is not auto-updated.

Last update: 2024-09-28 16:57:05 UTC


README

组件库包含用于处理 REST 请求的独立操作。

安装

安装此扩展的首选方式是通过 composer

运行以下命令之一:

$ composer require "webulla/yii2-rest":"*"

配置

在我的项目中,我使用 Backbone 在客户端处理模型。因此,所有来自模型的 ajax 请求(方法 Backbone.sync())被分为四种类型:GETPOSTPUTDELETE。为了处理这些请求,我实现了独立操作。

我将立即提供一个示例,这将更容易理解如何使用此组件。以下是一个用于处理帖子的控制器模型示例。

namespace app\controllers;

use Yii;
use app\models\Post;
use webulla\rest\actions\RestAction;

/**
 * PostController implements the CRUD actions for Post model.
 */
class PostController extends \app\components\web\Controller {

	/**
	 * @inheritdoc
	 */
	public function actions() {
		return [
			'rest' => [
				'class' => RestAction::className(),
				'modelClass' => Post::className(),
			],
		];
	}
}

设置详细说明

...
'rest' => [
    // action class
    'class' => RestAction::className(),

    // model class
    'modelClass' => Post::className(),

    // allowed methods for request
    // default: ['get', 'post', 'put', 'delete']
    'methods' => ['get', 'post', 'put', 'delete'],
],
...

允许以下类型的查询

  • get - 获取现有模型;
  • post - 创建新模型;
  • put - 更新现有模型;
  • delete - 删除现有模型。

如果您使用以下方法之一(get、put、delete)传输数据,则还必须传递模型的主键(id 属性)

yoursite.com/post/rest?id=1

您还可以为您的 REST API 使用短 URL。为此,请配置配置文件中的组件 urlManager

...
'urlManager' => [
    // request query "/controller/action?id=1" instead of "?r=controller/action&id=1"
    'enablePrettyUrl' => true,

    // request query "/controller/action" instead of "index.php/controller/action"
    'showScriptName' => false,

    'rules' => [
        // default rule
        'post/rest' => '/post/rest',

        // allow "/post/rest/1" request instead of "/post/rest?id=1"
        'post/rest/<id:\d+>' => '/post/rest',
    ]
],

用法

一个简单的示例,通过模型 REST API 接收数据

$(function() {
    $.ajax({
        url: '/post/rest?id=23',
        type: 'get',
        dataType: 'json',

        success: function(attributes) {
            console.log(attributes);
        }
    });
});

响应

{
	"id":"23",
	"user_id":"1",
	"content":"Text here",
	"created_at":"2015-04-04 14:08:10",
	"updated_at":"2015-04-04 14:08:20"
}

安全性

在我的项目中通过 JavaScript 使用 REST API,我添加了保护您数据的功能:您可以明确指定每种请求类型的哪些安全属性。有三种配置安全属性的方式

  • 通过 REST API 保存任何数据(postput)时,模型以 rest-save 方案创建。
  • 通过 REST API 获取一些数据(get)时,模型以 rest-fetch 方案创建。

这是我在 REST 请求中使用的 Post 模型

class Post extends \yii\db\ActiveRecord {
    ...
	/**
	 * @inheritdoc
	 */
	public function rules() {
		return [
			...
			// this validator boosted sets the form while preserving the model through the rest api
			[['user_id'], ForceValueValidator::className(), 'value' => Yii::$app->user->getId(), 'on' => 'rest-save'],
		];
	}

	/**
	 * @inheritdoc
	 */
	public function scenarios() {
		return array_merge(parent::scenarios(), [
		    // these attributes are writable by rest api
			'rest-save' => ['user_id', 'content'],

			// these attributes can be read through the rest api
			'rest-fetch' => ['id', 'user_id', 'content', 'created_at', 'updated_at'],
		]);
	}
    ...
}