vergelijkgroep / yii2-json-behavior
Yii2 json encoding and decoding attribute behavior
Installs: 905
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 2
Forks: 0
Open Issues: 0
Type:yii2-extension
pkg:composer/vergelijkgroep/yii2-json-behavior
Requires
- php: >=5.2.0
- ext-json: *
- yiisoft/yii2: ~2.0.12
This package is auto-updated.
Last update: 2025-11-09 15:15:30 UTC
README
Automatically encode/decode attribute values in JSON via Yii2 Behavior.
Install
Install via Composer:
composer require vergelijkgroep/yii2-json-behavior
or add
"vergelijkgroep/yii2-json-behavior" : "*"
to the require section of your composer.json file.
Usage
JsonBehavior
Configure your model:
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 ] ]; } }
The attributes will now automatically be encoded and decoded:
$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
The emptyValue is the value of the attribute when its null after decoding from JSON. Default is null.
asArray
The asArray option defines the JSON decoding format, true for associative array, false for object. Default is false.
License
This software is distributed under the MIT license.