Skip to content

Latest commit

 

History

History
87 lines (72 loc) · 3.36 KB

File metadata and controls

87 lines (72 loc) · 3.36 KB

Extending Functionality With Traits

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.

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