When used together with events, behaviors are even more powerful. A behavior, when being attached to a component, can attach some of its methods to some events of the component. By doing so, the behavior gets a chance to observe or change the normal execution flow of the component.
很是不能理解:A behavior, when being attached to a component, can attach some of its methods to some events of the component。行为可以绑定它的一个方法到component的事件上去?
class CModelBehavior extends CBehavior
{
public function events()
{
return array(
'onBeforeValidate'=>'beforeValidate',
'onAfterValidate'=>'afterValidate',
);
}
public function beforeValidate($event)
{
}
public function afterValidate($event)
{
}
}
class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe;
public function behaviors()
{
return array(
'FormBehavior'=>array('class'=>'AllFieldsRequired'));
}
}
class AllFieldsRequired extends CModelBehavior
{
public function beforeValidate($event)
{
$form = $event->sender;
foreach($form->getAttributes() as $name => $value)
{
if($value == '')
{
$form->addError($name,"$name cannot be blank!!");
}
}
$event->isValid = !$form->hasErrors();
}
}