Sarah West
Sarah West

Reputation: 2037

Yii2 attributeLabels()

I have an ActiveRecord Model with this function for attribute labels:

public function attributeLabels() { 

        return  [
            'start_date' => Text::getText('model_group_StartDate'),
            // and many more texts ....
        ];
}

Now my problem is that when I use ActiveForm and let Yii load the labels automatically that it produces too many sql queries because everytime it loads a label it calls attributeLabels() and slows down my page.

I have to load the attribute labels from database.

I know that I can set own labels in ActiveForm via label() but I prefer having it in my model because I have to use the labels on different places.

I'm happy about any hints how to load the attribute labels only once.

Upvotes: 2

Views: 3146

Answers (1)

laszlovl
laszlovl

Reputation: 491

Yii will indeed call your function attributeLabels() (and thus execute Text::getText()) every time an individual attribute label is requested.

You could solve this by caching the generated attribute labels on the class level, which means a label will only have to be generated once for each combination of {class, attribute} per request. If you have a common class that all of your ActiveRecord classes extend from, you can solve it once and for all with code like this:

class ActiveRecord extends \yii\db\ActiveRecord {
    private static $getAttributeLabelCache;

    public function getAttributeLabel($attribute)
    {
        $class = get_class($this);

        if (!isset(self::$getAttributeLabelCache[$class][$attribute])) {
            self::$getAttributeLabelCache[$class][$attribute] = parent::getAttributeLabel($attribute);
        }

        return self::$getAttributeLabelCache[$class][$attribute];
    }
}

Somewhat related: https://github.com/laszlovl/yii2-staticactiverecord

Upvotes: 3

Related Questions