What Is Event In Yii? How To Use Event In Yii?

What is event in yii? How to use event in yii?

Example:


public function onForestRan($event){

    $this->raiseEvent('onForestRan', $event);

}

$myComponent->onForestRan = array(new SomeOtherClass, 'eventHandler1');

When the event is triggered?

Hi, create this controller and run it, i think once you do this everything will make sense to you :)




class SomeController extends CController

{

    protected $number = 0;

    

    public function init()

    {

        parent::init();

        

        $this->onBeforeHelloWorld = array($this, 'firstHelloCallback');

        $this->attachEventHandler('onBeforeHelloWorld', array($this, 'secondHelloCallback'));

        $this->onBeforeHelloWorld = array($this, 'thirdHelloCallback');

        

        $this->onAfterHelloWorld = array($this, 'firstByeCallback');

        $this->attachEventHandler('onAfterHelloWorld', array($this, 'secondByeCallback'));

        $this->onAfterHelloWorld = array($this, 'thirdByeCallback');

    }

    

    public function onBeforeHelloWorld()

    {

        $this->raiseEvent('onBeforeHelloWorld', new CEvent($this));

    }

    

    public function onAfterHelloWorld(CEvent $event)

    {

        $this->raiseEvent('onAfterHelloWorld', $event);

    }

    

    public function actionIndex()

    {

        $this->onBeforeHelloWorld();

        echo 'Hello world!!! <hr />';

        $this->onAfterHelloWorld(new CEvent($this, array('otherNumber' => 12345)));

    }

    

    public function firstHelloCallback($event)

    {

        echo 'I am in the first hello callback<br />';

        $this->number = $event->params['number'] = 1024;

    }

    

    public function secondHelloCallback($event)

    {

        echo sprintf('I am in the second hello callback and i have the number %d <br />', $event->params['number']);

        $this->number = $event->params['number'] = 2048;

    }

    

    public function thirdHelloCallback($event)

    {

        echo sprintf('I am in the third hello callback and i have the number %d <br />', $event->params['number']);

    }


    public function firstByeCallback($event)

    {

        echo sprintf('I am in the first after hello callback and i can see a previous callback has set the $number to be %d<br />', $this->number);

        echo sprintf('The default value for $otherNumber is %d <br />', $event->params['otherNumber']);

        $event->params['otherNumber'] = 100;

    }

    

    public function secondByeCallback($event)

    {

        echo sprintf('I am in the second after hello callback and i have the otherNumber set to %d <br />', $event->params['otherNumber']);

        $event->params['otherNumber'] = 200;

    }

    

    public function thirdByeCallback($event)

    {

        echo sprintf('I am in the third after hello callback and i have the otherNumber %d <br />', $event->params['otherNumber']);

    }


}