The library provides several optional traits that can be used to extend the functionality of ActiveRecord models.
These traits can be included in your model classes to add specific behaviors or features. All traits are optional
and should be used based on your specific needs.
- ArrayableTrait provides
toArray()method to convert a model to an array format; - ArrayAccessTrait allows accessing model properties and relations using array syntax;
- ArrayIteratorTrait allows accessing model properties and relations iteratively;
- CustomConnectionTrait allows using a custom database connection for a model;
- CustomTableNameTrait allows using a custom table name for a model;
- EventsTrait allows using events and handlers for a model;
- FactoryTrait allows creating models and relations using yiisoft/factory;
- MagicPropertiesTrait stores properties in a private property and provides magic getters and setters for accessing the model properties and relations;
- MagicRelationsTrait allows using methods with prefix
getand suffixQueryto define relations (e.g.getOrdersQuery()forordersrelation); - PrivatePropertiesTrait allows using private properties in a model;
- RepositoryTrait provides methods to interact with a model as a repository.
All traits are optional and can be used as needed. They can be combined to create models with the desired functionality.
Important
Magic-related traits (MagicPropertiesTrait and MagicRelationsTrait) are optional convenience features.
They are not required for using Active Record. For better performance and type safety, consider using explicit
property definitions (public, protected, or private) and explicit relation definitions via relationQuery() method.
For example, to create an Active Record class that supports array access and can be converted to an array:
use Yiisoft\ActiveRecord\ActiveRecord;
use Yiisoft\ActiveRecord\Trait\ArrayableTrait;
use Yiisoft\ActiveRecord\Trait\ArrayAccessTrait;
use Yiisoft\ActiveRecord\Trait\ArrayIteratorTrait;
class ArrayActiveRecord extends ActiveRecord
{
use ArrayableTrait;
use ArrayAccessTrait;
use ArrayIteratorTrait;
}Then you can create your model class by extending ArrayActiveRecord:
final class User extends ArrayActiveRecord
{
protected int $id;
protected string $username;
protected string $email;
protected string $status = 'active';
}Another example, to create an Active Record class that uses magic properties and relations:
use Yiisoft\ActiveRecord\ActiveRecord;
use Yiisoft\ActiveRecord\Trait\MagicPropertiesTrait;
use Yiisoft\ActiveRecord\Trait\MagicRelationsTrait;
class MagicActiveRecord extends ActiveRecord
{
use MagicPropertiesTrait;
use MagicRelationsTrait;
}Then you can create your model class by extending MagicActiveRecord:
/**
* Entity User.
*
* @property int $id
* @property string $username
* @property string $email
* @property string $status
*/
final class User extends MagicActiveRecord
{
}Back to README