Say i have a model for a contest table, and i have a property called "name" that defines the name of the contest.
Now, i want to be able to attach distinct events for this property, for example, before i echo it in frontend i want to CHtml::encode() it, or say i have a component that i plug in and that component has a method which transforms the name in uppercase or makes it bold or similar behavior(if you are familiar with wordpress, think at add_filters() functionality), basically i want to let an open door to change this property before i retrieve it.
Right now i have something like:
<?php
//model class
class Contest extends CActiveRecord
{
public function onBeforeGetName($event)
{
$this->raiseEvent('onBeforeGetName', $event);
}
public function beforeGetName()
{
if($this->hasEventHandler('onBeforeGetName'))
{
$event=new CModelEvent($this);
$this->onBeforeGetName($event);
return $event->isValid;
}
else
return true;
}
public function getName()
{
$this->beforeGetName();
return $this->name;
}
[...]
[...]
}
So i added an event handler to be executed right before i request the name property of my model
My controller looks like:
<?php
class SiteController extends CmsFrontendController
{
private $model;
public function actionTest()
{
$this->model=Contest::model()->findByPk(20);
$this->model->attachEventHandler('onBeforeGetName', array($this, 'upperName'));
$this->model->getEventHandlers('onBeforeGetName')->add(array($this, 'boldName'));
echo $this->model->getName();
}
public function upperName()
{
$this->model->name=strtoupper($this->model->name);
}
public function boldName()
{
$this->model->name='<b>'.$this->model->name.'</b>';
}
[...]
[...]
}
All this seems correct to you ?
I mean, it looks a bit messy from my point of view, but once again, as i stated, i don’t fully understand the events mechanism in yii.
LE:
But what if i need to attach this event handler to a component, what do i do then , because i don’t have access to the model instance anymore ($this->model from the controller in my case)