Skip to content

Latest commit

 

History

History
114 lines (83 loc) · 2.02 KB

SerializeBehavior.md

File metadata and controls

114 lines (83 loc) · 2.02 KB

SerializeBehavior

This extension will help you to create a virtual field for your ActiveRecord models which will store the serialized data in one of the fields of the model.

Using

$model = new News();
$model->save();

print_r($model->_data); // null
print_r($model->title); // null
print_r($model->meta['keywords']); // null

print_r($model->is_active); // true
$model->is_active = 1;
print_r($model->getOldAttribute('is_active')); // null

$model->save();
print_r($model->_data); // {"is_active": 1}

Configuration

Options

storageAttribute

  • Type: string
  • Require: true
  • Example: 'data'

Field in the database in which all data will be stored

attributes

  • Type: array
  • Require: true
  • Example:
'attributes' => [
    // simple text field
    'description', 
    
    // field in the form of an array that will be used by default
    'meta' => [ 
        'keywords' => null,
        'description' => null,
    ],
    
    // default value
    'is_active' => true,

    // callback as default value
    'date' => function() {
        return $this->updated_at ?: $this->created_at;
    }
]

A list of virtual fields that will be stored in the storageAttribute

encode

  • Type: \Closure | array | string | bool
  • Require: false
  • Default: yii\helpers\Json::encode
  • Example:
// 'encode' => 'serialize',
'encode' => function($value) {
    return serialize($value);
},

or

'encode' => function($value) {
    return new \yii\db\JsonExpression($value);
},

or if you do not need to encode

'encode' => false,

Method that will be used to encode data

decode

  • Type: \Closure | array | string | bool
  • Require: false
  • Default: yii\helpers\Json::decode
  • Example:
// 'decode' => 'unserialize',
'decode' => function($value) {
    return unserialize($value); 
},

or if you do not need to decode, the database returns an array

'decode' => false, 

Method that will be used to decode data