A
A
Airat Khisyamov2015-12-23 21:18:37
Yii
Airat Khisyamov, 2015-12-23 21:18:37

Yii2. How to dynamically connect to the Validotor class "MyBehavior" (Yii2 Behavior) so that all built In Validators inherit it?

Hello Colleagues
Perhaps someone can help.
I want to dynamically connect the behavior "MyValidationBehavior" (Yii2 Behavior) to all validators of the yii\validators\Validator base class of my project.
I wrote a code that adds my "MyValidationBehavior" one to each class.
I add "MyValidationBehavior" for all built In Validators

foreach (\yii\validators\Validator::$builtInValidators as $builtInValidator)
 {
$container->set($builtInValidator, 
["as $builtInValidator" => ['class' => MyValidationBehavior::className(),]] );
 }

But, I want to connect the behavior dynamically only for the base class, so that the rest of the validation classes inherit the behavior of the base class.
Do you think it's possible?
What I dug up:
1. If I connected the behavior through Component::$behaviors[]
then the inherited classes have the behavior specified in the base one.
2. I tried to connect dynamically my behavior to "\yii\validators\Validator" but without success, the descendant classes were without my behavior.
Trying example:
$container = \Yii::$container;
 //вариант 1
$container->set('\yii\validators\Validator',
["as Validator" => ['class' => MyValidationBehavior::className(),]]);
//вариант 2
$validator = $container->get('yii\validators\Validator');
$validator->attachBehavior('Validator', MyValidationBehavior::className());

If you need more information, I'll try to answer.
Thanks!)
PS

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
LAV45, 2017-03-23
@LAV45

You can statically hang a handler on all events of the base class.
This is how I added my handler to all controllers

\yii\base\Event::on('yii\base\Controller', 'beforeAction', function(\yii\base\ActionEvent $event) {
// ...
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question