supplyhog / yii2-json-object-behavior
dev-master
2016-02-26 16:42 UTC
Requires
- php: >=5.4.0
- yiisoft/yii2: *
Requires (Dev)
- phpunit/phpunit: ^5.1
This package is not auto-updated.
Last update: 2024-09-26 00:14:36 UTC
README
#yii2-json-object-behavior
##安装 通过 composer 安装此扩展。将以下行添加到您的项目 composer.json 文件中
supplyhog/yii2-json-object-behavior” : “dev-master”
##功能介绍
数据库中的 JSON 字符串字段在 yii\db\ActiveRecord
上成为可用的对象或对象数组。在保存时无需将其转换回字符串。只需像使用属性一样使用它。
##行为配置
public function behaviors() { return [ //It is best to name your behaviors so that you can use more than one 'field_behavior' => [ 'class' => 'supplyhog\JsonObjectBehavior\JsonObjectBehavior', 'attribute' => 'field', //Name of the attribute that holds the JSON string 'objectClass' => JsonObjectModel::className(), //Replace with your own class that extends JsonObjectModel 'init' => true, // (new Model())->field will be an object // 'default' => [], // If you need defaults ], 'field_array_behavior' => [ 'class' => 'supplyhog\JsonObjectBehavior\JsonObjectBehavior', 'attribute' => 'fieldArray', //Name of the attribute that holds the JSON string 'array' => true, //This is an array of objects 'init' => true, // (new Model())->fieldArray will be an array 'default' => [ //Object defaults. Useful sometimes. The field value 'class' => JsonObjectModel::className(), //Replace with your own class that extends JsonObjectModel 'hello' => 'world', // the attribute hello will be set to "world" if the JSON string does not have a value for it ], ], ]; }
##JsonObjectModel
此部分提供用于将您的 JSON 字符串转换为基类。它扩展了 \yii\base\Model
,这非常有用。这不是必需的,但如果您使用自己的,请确保查看 JsonObjectModel 中的魔法方法 __toString()
并将其复制到您的模型中。