vergelijkgroep / yii2-json-behavior
Yii2 json 编码和解码属性行为
v1.0.1
2019-12-06 14:12 UTC
Requires
- php: >=5.2.0
- ext-json: *
- yiisoft/yii2: ~2.0.12
This package is auto-updated.
Last update: 2024-08-30 01:08:11 UTC
README
通过 Yii2 Behavior 自动编码/解码属性值
安装
通过 Composer 安装
composer require vergelijkgroep/yii2-json-behavior
或添加
"vergelijkgroep/yii2-json-behavior" : "*"
到您的 composer.json
文件的 require
部分。
用法
JsonBehavior
配置您的模型
use vergelijkgroep\JsonBehavior\JsonBehavior; class Item extends \yii\db\ActiveRecord { public function behaviors() { return [ [ 'class' => JsonBehavior::class, 'attributes' => ['attribute1', 'attribute2'], 'emptyValue' => 'empty_value', // optional 'asArray' => true, // optional ] ]; } }
属性现在将自动编码和解码
$item = Item::findOne(1); $item->attribute1['foo'] = 'bar'; $item->attribute2 = null; $item->save(); // attribute1 will be encoded and saved as json $item = Item::findOne(1); echo $item->attribute1['foo']; // 'bar' echo $item->attribute2; // 'empty_value'
emptyValue
emptyValue
是从 JSON 解码后属性值为 null
的值。默认为 null
。
asArray
asArray
选项定义了 JSON 解码格式,true 为关联 array
,false 为 object
。默认为 false。
许可证
此软件在 MIT 许可证下分发。