simialbi/yii2-rest-client

Yii Framework 2.0 的 REST 客户端(类似 AR 模型)(通过 yii2-http-client,扩展 ApexWire/yii2-restclient)

安装数: 12 127

依赖者: 1

建议者: 0

安全: 0

星标: 20

关注者: 4

分支: 11

开放问题: 1

类型:yii2-extension

2.0.0 2022-07-28 07:23 UTC

README

此扩展提供了一个接口,通过 ActiveRecord 类似的模型在 Yii 2 中与 RESTful API 交互。它基于 ApexWireyii2-restclient

Latest Stable Version Total Downloads License Build Status

资源

安装

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

运行以下命令之一:

$ php composer.phar require --prefer-dist simialbi/yii2-rest-client

或添加以下内容到您的 composer.json 文件的 require 部分:

"simialbi/yii2-rest-client": "*"

配置

要使用此扩展,请在您的应用程序配置中配置 restclient 组件

    'components' => [
        'rest' => [
            'class' => 'simialbi\yii2\rest\Connection',
            'baseUrl' => 'https://api.site.com/',
            // 'auth' => function (simialbi\yii2\rest\Connection $db) {
            //      return 'Bearer: <mytoken>';
            // },
            // 'auth' => 'Bearer: <mytoken>',
            // 'usePluralisation' => false,
            // 'useFilterKeyword' => false,
            // 'enableExceptions' => true,
            // 'itemsProperty' => 'items'
        ],
    ],

使用方法

定义您的模型

<?php

namespace app\models;

use simialbi\yii2\rest\ActiveRecord;

/**
 * MyModel
 * 
 * @property integer $id
 * @property string $name
 * @property string $description 
 * 
 * @property-read MyOtherModel $myOtherModel
 */
class MyModel extends ActiveRecord {
    /**
     * {@inheritdoc}
     */
    public static function modelName() {
        return 'my-super-model-name';
    }

    /**
     * {@inheritdoc}
     */
    public static function primaryKey() {
        return ['id'];
    }
}

/**
 * Class MyOtherModel
 * 
 * @property integer $id
 * @property integer $my_model_id
 * @property string $subject
 * 
 * @property-read MyModel[] $myModels
 */
class MyOtherModel extends ActiveRecord {
    /**
     * {@inheritdoc}
     */
    public static function primaryKey() {
        return ['id'];
    }
}

您需要通过覆盖 primaryKey() 方法来定义主键,否则您将获得异常。如果您没有覆盖 modelName() 方法,它将根据类名猜测它(例如,MyModel 变为 my-model)。它与 simialbi\yii2\rest\Connection::$baseUrl 一起用于生成 URL。

定义活动记录(规则、行为等)的用法与 yii\db\ActiveRecord 相同。

重要:请确保您像上面示例中那样定义对象的属性(例如,PHPdoc 中的 @property 语法)或覆盖 attributes() 方法以返回数组形式的允许属性

同样关于关系。请确保您通过 @property-read PHPdoc 注释定义它们,或覆盖 getRelations 方法。如果相关类与主类不使用相同的命名空间,请确保使用完全限定类名(例如,@property-read \app\models\OtherModel[] $otherModels

许可证

yii2-rest-client 在 MIT 许可证下发布。有关详细信息,请参阅捆绑的 LICENSE

致谢