Skip to content
PHP Ecosystem
Explore

AttributeTypecastBehavior

API reference › yii › behaviors › AttributeTypecastBehavior

classyii\behaviors\AttributeTypecastBehavior
Extendsyii\base\Behavior » yii\base\BaseObject
Implementsyii\base\Configurable
Since2.0.10
Sourceframework/behaviors/AttributeTypecastBehavior.php

AttributeTypecastBehavior provides an ability of automatic model attribute typecasting.

This behavior is very useful in case of usage of ActiveRecord for the schema-less databases like MongoDB or Redis. It may also come in handy for regular ActiveRecord or even Model, allowing to maintain strict attribute types after model validation.

This behavior should be attached to Model or BaseActiveRecord descendant.

You should specify exact attribute types via $attributeTypes.

For example:

use yii\behaviors\AttributeTypecastBehavior;
class Item extends \yii\db\ActiveRecord
{
public function behaviors()
{
return [
'typecast' => [
'class' => AttributeTypecastBehavior::class,
'attributeTypes' => [
'amount' => AttributeTypecastBehavior::TYPE_INTEGER,
'price' => AttributeTypecastBehavior::TYPE_FLOAT,
'is_active' => AttributeTypecastBehavior::TYPE_BOOLEAN,
],
'typecastAfterValidate' => true,
'typecastBeforeSave' => false,
'typecastAfterFind' => false,
],
];
}
// ...
}

Tip: you may left $attributeTypes blank - in this case its value will be detected automatically based on owner validation rules. Following example will automatically create same $attributeTypes value as it was configured at the above one:

use yii\behaviors\AttributeTypecastBehavior;
class Item extends \yii\db\ActiveRecord
{
public function rules()
{
return [
['amount', 'integer'],
['price', 'number'],
['is_active', 'boolean'],
];
}
public function behaviors()
{
return [
'typecast' => [
'class' => AttributeTypecastBehavior::class,
// 'attributeTypes' will be composed automatically according to `rules()`
],
];
}
// ...
}

This behavior allows automatic attribute typecasting at following cases:

  • after successful model validation
  • before model save (insert or update)
  • after model find (found by query or refreshed)

You may control automatic typecasting for particular case using fields $typecastAfterValidate, $typecastBeforeSave and $typecastAfterFind. By default typecasting will be performed only after model validation.

Note: you can manually trigger attribute typecasting anytime invoking typecastAttributes() method:

$model = new Item();
$model->price = '38.5';
$model->is_active = 1;
$model->typecastAttributes();
PropertyTypeDescriptionDefined by
$attributeTypesarray|nullAttribute typecast map in format: attributeName => type. Default: null.AttributeTypecastBehavior
$owneryii\behaviors\T|nullThe owner of this behavior. Default: null.AttributeTypecastBehavior
$skipOnNullboolWhether to skip typecasting of null values. Default: true.AttributeTypecastBehavior
$typecastAfterFindboolWhether to perform typecasting after retrieving owner model data from the database (after find or refresh). Default: false.AttributeTypecastBehavior
$typecastAfterSaveboolWhether to perform typecasting after saving owner model (insert or update). Default: false. Available since 2.0.14.AttributeTypecastBehavior
$typecastAfterValidateboolWhether to perform typecasting after owner model validation. Default: true.AttributeTypecastBehavior
$typecastBeforeSaveboolWhether to perform typecasting before saving owner model (insert or update). Default: false.AttributeTypecastBehavior
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\BaseObject
__get()Returns the value of an object property.yii\base\BaseObject
__isset()Checks if a property is set, i.e. defined and not null.yii\base\BaseObject
__set()Sets value of an object property.yii\base\BaseObject
__unset()Sets an object property to null.yii\base\BaseObject
afterFind()Handles owner ‘afterFind’ event, ensuring attribute typecasting.AttributeTypecastBehavior
afterSave()Handles owner ‘afterInsert’ and ‘afterUpdate’ events, ensuring attribute typecasting.AttributeTypecastBehavior
afterValidate()Handles owner ‘afterValidate’ event, ensuring attribute typecasting.AttributeTypecastBehavior
attach()Attaches the behavior object to the component.AttributeTypecastBehavior
beforeSave()Handles owner ‘beforeInsert’ and ‘beforeUpdate’ events, ensuring attribute typecasting.AttributeTypecastBehavior
canGetProperty()Returns a value indicating whether a property can be read.yii\base\BaseObject
canSetProperty()Returns a value indicating whether a property can be set.yii\base\BaseObject
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
clearAutoDetectedAttributeTypes() staticClears internal static cache of auto detected $attributeTypes values over all affected owner classes.AttributeTypecastBehavior
detach()Detaches the behavior object from the component.yii\base\Behavior
events()Declares event handlers for the $owner’s events.AttributeTypecastBehavior
hasMethod()Returns a value indicating whether a method is defined.yii\base\BaseObject
hasProperty()Returns a value indicating whether a property is defined.yii\base\BaseObject
init()Initializes the object.yii\base\BaseObject
typecastAttributes()Typecast owner attributes according to $attributeTypes.AttributeTypecastBehavior
detectAttributeTypes() protectedComposes default value for $attributeTypes from the owner validation rules.AttributeTypecastBehavior
resetOldAttributes() protectedResets the old values of the named attributes.AttributeTypecastBehavior
typecastValue() protectedCasts the given value to the specified type.AttributeTypecastBehavior
ConstantValueDescriptionDefined by
TYPE_INTEGER'integer'AttributeTypecastBehavior
TYPE_FLOAT'float'AttributeTypecastBehavior
TYPE_BOOLEAN'boolean'AttributeTypecastBehavior
TYPE_STRING'string'AttributeTypecastBehavior
public array|null $attributeTypes = null

Attribute typecast map in format: attributeName => type.

Type can be set via PHP callable, which accept raw value as an argument and should return typecast result. For example:

[
'amount' => 'integer',
'price' => 'float',
'is_active' => 'boolean',
'date' => function ($value) {
return ($value instanceof \DateTime) ? $value->getTimestamp(): (int) $value;
},
]

If not set, attribute type map will be composed automatically from the owner validation rules.

public bool $skipOnNull = true

Whether to skip typecasting of null values.

If enabled attribute value which equals to null will not be type-casted (e.g. null remains null), otherwise it will be converted according to the type configured at $attributeTypes.

public bool $typecastAfterFind = false

Whether to perform typecasting after retrieving owner model data from the database (after find or refresh).

This option may be disabled in order to achieve better performance. For example, in case of ActiveRecord usage, typecasting after find will grant no benefit in most cases an thus can be disabled. Note that changing this option value will have no effect after this behavior has been attached to the model.

public bool $typecastAfterSave = false

Whether to perform typecasting after saving owner model (insert or update).

This option may be disabled in order to achieve better performance. For example, in case of ActiveRecord usage, typecasting after save will grant no benefit an thus can be disabled. Note that changing this option value will have no effect after this behavior has been attached to the model.

Since

2.0.14

public bool $typecastAfterValidate = true

Whether to perform typecasting after owner model validation.

Note that typecasting will be performed only if validation was successful, e.g. owner model has no errors. Note that changing this option value will have no effect after this behavior has been attached to the model.

public bool $typecastBeforeSave = false

Whether to perform typecasting before saving owner model (insert or update).

This option may be disabled in order to achieve better performance. For example, in case of ActiveRecord usage, typecasting before save will grant no benefit an thus can be disabled. Note that changing this option value will have no effect after this behavior has been attached to the model.

public function afterFind(yii\base\Event $event): mixed

Handles owner ‘afterFind’ event, ensuring attribute typecasting.

Parameters

ParameterTypeDescription
$eventyii\base\EventEvent instance.

Returns

mixed

public function afterSave(yii\base\Event $event): mixed

Handles owner ‘afterInsert’ and ‘afterUpdate’ events, ensuring attribute typecasting.

Parameters

ParameterTypeDescription
$eventyii\base\EventEvent instance.

Returns

mixed

Since

2.0.14

public function afterValidate(yii\base\Event $event): mixed

Handles owner ‘afterValidate’ event, ensuring attribute typecasting.

Parameters

ParameterTypeDescription
$eventyii\base\EventEvent instance.

Returns

mixed

public function attach(mixed $owner): mixed

Attaches the behavior object to the component.

The default implementation will set the $owner property and attach event handlers as declared in events(). Make sure you call the parent implementation if you override this method.

Parameters

ParameterTypeDescription
$ownermixedThe component that this behavior is to be attached to.

Returns

mixed

public function beforeSave(yii\base\Event $event): mixed

Handles owner ‘beforeInsert’ and ‘beforeUpdate’ events, ensuring attribute typecasting.

Parameters

ParameterTypeDescription
$eventyii\base\EventEvent instance.

Returns

mixed

public static function clearAutoDetectedAttributeTypes(): mixed

Clears internal static cache of auto detected $attributeTypes values over all affected owner classes.

Returns

mixed

public function events(): array

Declares event handlers for the $owner’s events.

Child classes may override this method to declare what PHP callbacks should be attached to the events of the $owner component.

The callbacks will be attached to the $owner’s events when the behavior is attached to the owner; and they will be detached from the events when the behavior is detached from the component.

The callbacks can be any of the following:

  • method in this behavior: 'handleClick', equivalent to [$this, 'handleClick']
  • object method: [$object, 'handleClick']
  • static method: ['Page', 'handleClick']
  • anonymous function: function ($event) { ... }

The following is an example:

[
Model::EVENT_BEFORE_VALIDATE => 'myBeforeValidate',
Model::EVENT_AFTER_VALIDATE => 'myAfterValidate',
]

Returns

array: Events (array keys) and the corresponding event handler methods (array values).

public function typecastAttributes(array|null $attributeNames = null): mixed

Typecast owner attributes according to $attributeTypes.

Parameters

ParameterTypeDescription
$attributeNamesarray|nullList of attribute names that should be type-casted. If this parameter is empty, it means any attribute listed in the $attributeTypes should be type-casted.

Returns

mixed

protected function detectAttributeTypes(): array

Composes default value for $attributeTypes from the owner validation rules.

Validators that have a when condition are ignored: the detection result is composed once per owner class, while such a condition can only be resolved against a particular model instance at validation time. Type-casting an attribute whose rule may not even be applied would convert a value that has never been validated, so attributes covered by conditional rules only are left out of the map. Specify $attributeTypes explicitly if you need them to be type-casted.

Returns

array: Attribute type map.

protected function resetOldAttributes(): mixed

Resets the old values of the named attributes.

Returns

mixed

protected function typecastValue(mixed $value, string|callable $type): mixed

Casts the given value to the specified type.

Parameters

ParameterTypeDescription
$valuemixedValue to be type-casted.
$typestring|callableType name or typecast callable.

Returns

mixed: Typecast result.