minity / yii2-model-setup
Configure all the model aspects in one place.
v0.1.0
2017-10-22 23:02 UTC
Requires (Dev)
- phpunit/phpunit: ^6.2
- yiisoft/yii2: ^2.0@dev
This package is auto-updated.
Last update: 2025-09-28 17:07:48 UTC
README
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.
Example
Usually, creating any ActiveRecord model we must define several methods, such tableName(),
attributeLabels(), attributeHints(), rules() and fields().
Using \Minity\ModelSetup\ActiveRecordConfigurationTrait all we need is define setup()
method as below
<?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.