In-one-place configuration for Yii2 models
If you feel uncomfortable to looking up dozen of methods while adding
or checking up a property of Yii2 model, consider to use this traits., (*1)
Example
Usually, creating any ActiveRecord model we must define several methods, such tableName()
,
attributeLabels()
, attributeHints()
, rules()
and fields()
., (*2)
Using \Minity\ModelSetup\ActiveRecordConfigurationTrait
all we need is define setup()
method as below, (*3)
<?php
use Minity\ModelSetup\ActiveRecordConfigurationTrait;
use yii\db\ActiveRecord;
class Record extends ActiveRecord
{
use ActiveRecordConfigurationTrait;
protected static function setup() {
return [
'tableName' => '{{%record}}',
'attributes' => [
'field1' => [
'label' => 'Record Field 1',
'hint' => 'Record Hint 1',
'toArray' => 'record_field_1',
'rules' => ['required', ['number', 'min' => 0]],
],
'field2' => [
'label' => 'Record Field 2',
'hint' => 'Record Hint 2',
'toArray' => true, // the same as 'field2'
'rules' => ['string'],
],
'field3' => [
'label' => 'Record Field 3',
//'toArray' => false, // default
'rules' => ['safe'],
],
],
'relations' => [
'rel1' => ['hasOne', AnotherRecord::className(), ['id' => 'field1']],
'rel2' => ['hasMany', ViaRecord::className(), ['id' => 'via_id'],
'viaTable' => ['junction_table', ['rec_id' => 'id']],
],
]
];
}
}
Pay attention to the relations
section. You can see there a declarative way to define
relations, so you can get ActiveQuery object by calling $model->getRel1()
or get
ActiveRecord by calling $model->rel1
., (*4)