-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
Events can be used like filters #1212
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
It is already so. The |
|
Yes, but |
|
Since you pass in |
|
My way helps not only execute any function, but modify some variables also. I don't know that it is needed for core Yii functionality or not, but it give a great flexibility. add_filter( 'myfilter', $callbackFunctionForMyfilter);And in core: $oldResult=$result;
$result = apply_filters('myfilter', $oldResult);
//Now we have new $result variable that have been modified via 'myfilter'.
//It is convenient because anyone can modify $result for his own needs |
|
For an example how the current implementation works, see https://github.com/yiisoft/yii2/blob/master/framework/yii/base/Model.php#L321 The main change in your PR is that |
|
I don't understand. $this->on('myevent', 'myfunction');
/* .... */
$myEvent=newEvent;
$myEvent->myvar=$myvar;
$this->trigger('myevent', $myEvent);
/* We can't do anything with $myvar via Event System. I think it will be convenient to have ability to modify it */function myfunction($event)
{
/* We do anything here with $event */
return $event; //But the returned $event will vanish. We can't modify any variable here and return it in the client code
} |
function myfunction($event)
{
/* We do anything here with $event */
$event->myvar = 42;
}
$this->on('myevent', 'myfunction');
/* .... */
$myEvent=new MyEvent;
$myEvent->myvar=21;
$this->trigger('myevent', $myEvent);
echo $myEvent->myvar; // will be 42Objects are always given by reference in php. |
|
I dont' want annoy yii-developers but do you suppose that more useful for users will be a bit another code in https://github.com/yiisoft/yii2/blob/master/framework/yii/base/Model.php#L321? public function beforeValidate()
{
$event = new ModelEvent;
$event->model = $this; //Users will have access to object in callback
$this->trigger(self::EVENT_BEFORE_VALIDATE, $event);
return $event->isValid;
}And in ModelEvent class there will be |
|
|
|
Thanks for answers. It explains more things. The events work fine in Yii2. |
Is it possible to introlduce in Yii2 not simple Events only but Filters?
The defference is that the Event does things only, but Filter can be used for modification of variables. So we do something like:
So it is possible to modify variables using Events system. It is like wordpress filters.
Filters can be used in core Yii2. Suppose we have Response component and want modify it in yii\web\Application::handleRequest() method
Instead simple
return $response;we can do something like: