Creating Behaviors on Yii Framework

Last updated:

Behaviors are a good alternative to subclassing when it comes to sharing functionality among classes.

Yii Behaviors are a very elegant way to reuse functionality on the class level even though PHP itself only added Traits(a very close concept to Yii Behaviors) on version 5.4.

Creating a simple Behavior

p.s.: save this as SomeBehavior.php under protected/extensions

class SomeBehavior extends CBehavior{
    public function sayHello(){
        echo "hello"; 
    }
}

Using that Behavior in your class

p.s.: just using an AR model for example's sake; it could be any class at all.

class Person extends CActiveRecord{
    public function behaviors(){
        return array(
            'foo'=>array(
                 'class'=>'application.extensions.SomeBehavior'
        ));
    }

now, if you ever instantiate your Person class, you can call method sayHello() as if it had it!!

$p = new Person();
$p->sayHello();//'hello'

Extra Points: parameterizing (setting attributes to) Behaviors

You can also customize the behavior for each class that's using it. For example, say you have a behavior that you want to add a little flexibility to:

class CommunicateBehavior extends CBehavior{
    public $extraPolite=false;
    public function askQuestion($question){
        if($this->extraPolite){
            echo "Excuse me, sir, ".$question." ?";
        }else{
            echo $question." ?";
        }
    }
}

Then you can use it differently in each other class, for example:

class Brazilian extends Person{
    public function behaviors(){
        return array(
            'comm'=>array(
                'class'=>'path.to.CommunicationBehavior',
        ));
     }
}

or, for an Englishman:

class Englishman extends Person{
    public function behaviors(){
        return array(
            'comm'=>array(
                'class'=>'path.to.CommunicationBehavior',
                'extraPolite'=>true
        ));
     }
}

and each would ask a question in a different way:

$b = new Brazilian;
$b->askQuestion("what's the time");//what's the time?

but

$e = new Englishman;
$e->askQuestion("what's the time");//excuse me sir, what's the time?

This is really, really beautiful and powerful stuff. Always glad to have chosen Yii as my framework of choice.

w.i.p.: This is a work in progress. More content will hopefully be added for this.

Dialogue & Discussion