Search code examples
filteryiiyii2middleware

Is there anyway to get a variable from previous filter in Yii2?


In Yii2.0, I want to get a value from previous filter to avoid make the same query in every filter . Is there anyway to make it ?

For example , this is my code in a controller :

public function behaviors() {
    return [
        'filter1' => ['class' => Filter1::className()],
        'filter2' => ['class' => Filter2::className()]
    ];
}

In filter1 , I make a sql query, and I want use the result of this query in filter2 because I don't want make this query again.
How should I do ?
And if I want get a value from a filter in my controller, how should I do ?


Solution

  • Although you would be coupling your behaviors - you could access any behaviour through the component it is attached to

    \Yii::$app->controller->getBehavior('filter1')->yourValue
    

    or from filter2 behaviour:

    $this->owner->getBehaviour('filter1')->yourValue
    

    See

    http://www.yiiframework.com/doc-2.0/yii-base-behavior.html#$owner-detail