Traits

Yii2 using traits in a model and overriding them
Yii2 using traits in a model and overriding them

There’s a saying:

live and learn — and still die a fool

Why am I saying this? It’s about traits in PHP. They’ve been around for quite a while, but I only recently started using them in a new project.

The first thing I had to do was move the attributeLabels method into a trait. Yes, I could have created a single base class and extended it. But I decided to go with traits instead. So, here’s what we have:

namespace commontraitsobject;

use Yii;

trait ObjectModelTrait
{
    /**
     * Labels
     * @return array
     */
    public function attributeLabels()
    {
        return [
			'id' => Yii::t('app', 'ID'),
			'name' => Yii::t('app', 'Name'),
			'desc' => Yii::t('app', 'Description'),
			'index_id' => Yii::t('app', 'Index'),
			'is_active' => Yii::t('app', 'Is active'),
        ];
    }
}

This trait was reused multiple times in models. Here’s one example:

namespace commonmodelsterritory;

use yiidbActiveRecord;

use commontraitsobjectObjectModelTrait;

class TerritoryAreaModel extends ActiveRecord
{
	use ObjectModelTrait;
	
    public static function tableName()
    {
        return '{{%territory_area}}';
    }
}

read more...