How To Create A Yii Event And Handlers To It

I want to define event, and attach a handler to it.

But I found handler is not worked,why? Is there any errors?

my code is below:




class EventTest extends CEvent{

	//define a event

	public function onRun($event){

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

	}

}


class Notify {

	public static function notice($e){

		var_dump($e->sender instanceof TestController);

	}

	

	public function comment($e){

		echo 'comment handle';

	}

}


class TestController extends Controller{

	public function actionEventTest(){

		$et = new EventTest($this); //$this is sender of the event

		$et->onRun = array(new Notify(), 'comment');

	}

}






Try this way:





class EventTest extends CEvent

{

    public $myData;

}


class Notify extends CApplicationComponent

{


    public function comment($e)

    {

        echo 'comment handle';

        echo '<pre>';

        print_r($e);

        echo '</pre>';

        exit;

    }


}


class Users extends CActiveRecord 

{


    public static function model($className=__CLASS__) 

    {

        return parent::model($className);

    }


    public function processModel()

    {

        $event = new EventTest();

        $event->myData = 'Set some data';

        $this->onRun($event);

    }

    

    public function onRun($event)

    {

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

    }

}


class TestController extends Controller

{

    public function actionEventTest()

    {

        // make some logic

        

        $user = Users::model()->find();

        

        $user->onRun = array(new Notify(), 'comment');

        $user->processModel();

    }

}



Dear Friend

The following I hope would clear a bit.

protected/components/Greet.php




//Defining a Event Handler


class Greet{

	public function say($event){

		echo "hello ".$event->params['name'];

	}

	

}



protected/controllers/TestController.php




class TestController extends Controller{




	public function init(){  //Attaching the Event Handler...

		$this->onRun=array(new Greet,'say');

		

		}

//You can attach any number of handlers before raising the event.


        public function beforeAction($actionId){

//Attaching another handler before calling action...

		$this->onRun=function($event){echo "hi ".$event->params['name']." You are rising an event";};

		return true;

		}

	public function actionIndex(){

		$event=new CEvent($this,array('name'=>'seenivasan'));//Instantiating an CEvent with parameters for event handlers.

		$this->onRun($event);  //raising the event...

	

		}

	

	 public function onRun($event){  //Defining an Event...

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

		 }


	

	}