PHP code example of vergelijkgroep / yii2-json-behavior

1. Go to this page and download the library: Download vergelijkgroep/yii2-json-behavior library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

vergelijkgroep / yii2-json-behavior example snippets


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'