Send model attribute value to custom behavior

Hi everyone,

I’m currently implementing a behavior that will act on INSERT/UPDATE/DELETE events of a model, I need to pass some attributes of the model to the behavior, is this possible?

Right now I have a code similar to this one, but it’s not working:

Behavior class




<?php


namespace app\components;


use yii\base\Behavior;

use yii\db\ActiveRecord;




class TestBehavior extends Behavior

{

    public $var1;


    public function events()

    {

        return [

            ActiveRecord::EVENT_AFTER_INSERT => 'test',

            ActiveRecord::EVENT_AFTER_UPDATE => 'test',

            ActiveRecord::EVENT_AFTER_DELETE => 'test',

        ];

    }


    public function test()

    {

        echo($this->var1);

        die();

    }

}


?>



On the model:




 public function behaviors()

    {

        return [

            [

                'class' => 'app\components\TestBehavior',

                'var1' => $this->var1

            ],

        ];

    }



Am I interpreting behaviors in a wrong way?

Thank you

There is ‘owner’ attribute in behavior so if the model with behavior has got attribute ‘test’ you can get to this attribute by calling $this->owner->test in behavior.

Thanks