vergelijkgroep/yii2-json-behavior

Yii2 json encoding and decoding attribute behavior

v1.0.1 2019-12-06 14:12 UTC

This package is auto-updated.

Last update: 2024-12-09 13:30: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

MIT

This software is distributed under the MIT license.