Yii - Eventi

Puoi usare eventsper iniettare codice personalizzato in determinati punti di esecuzione. Puoi allegare codice personalizzato a un evento e, quando l'evento viene attivato, il codice viene eseguito. Ad esempio, un oggetto logger può attivare un fileuserRegisteredevento quando un nuovo utente si registra sul tuo sito web. Se una classe deve attivare eventi, è necessario estenderla dalla classe yii \ base \ Component.

Un gestore di eventi è un callback PHP. È possibile utilizzare i seguenti callback:

  • Una funzione PHP globale specificata come stringa.

  • Una funzione anonima.

  • Un array di un nome di classe e un metodo come stringa, ad esempio, ['ClassName', 'methodName']

  • Un array di un oggetto e un metodo come stringa, ad esempio, [$ obj, 'methodName']

Step 1 - Per allegare un gestore a un evento dovresti chiamare il yii\base\Component::on() metodo.

$obj = new Obj;
// this handler is a global function
$obj->on(Obj::EVENT_HELLO, 'function_name'); // this handler is an object method $obj->on(Obj::EVENT_HELLO, [$object, 'methodName']); // this handler is a static class method $obj->on(Obj::EVENT_HELLO, ['app\components\MyComponent', 'methodName']);
// this handler is an anonymous function

$obj->on(Obj::EVENT_HELLO, function ($event) {
   // event handling logic
});

Puoi allegare uno o più gestori a un evento. I gestori associati vengono chiamati nell'ordine in cui sono stati associati all'evento.

Step 2 - Per interrompere l'invocazione dei gestori, è necessario impostare il yii\base\Event::$handled property per true.

$obj->on(Obj::EVENT_HELLO, function ($event) { $event->handled = true;
});

Step 3 - Per inserire il gestore all'inizio della coda, puoi chiamare yii\base\Component::on(), passando false per il quarto parametro.

$obj->on(Obj::EVENT_HELLO, function ($event) {
   // ...
}, $data, false);

Step 4 - Per attivare un evento, chiama il yii\base\Component::trigger() metodo.

namespace app\components;
use yii\base\Component;
use yii\base\Event;
class Obj extends Component {
   const EVENT_HELLO = 'hello';
   public function triggerEvent() {
      $this->trigger(self::EVENT_HELLO);
   }
}

Step 5 - Per scollegare un gestore da un evento, è necessario chiamare il yii\base\Component::off() metodo.

$obj = new Obj; // this handler is a global function $obj->off(Obj::EVENT_HELLO, 'function_name');
// this handler is an object method
$obj->off(Obj::EVENT_HELLO, [$object, 'methodName']);
// this handler is a static class method
$obj->off(Obj::EVENT_HELLO, ['app\components\MyComponent', 'methodName']); // this handler is an anonymous function $obj->off(Obj::EVENT_HELLO, function ($event) {
   // event handling logic
});