Behaviors & events

Comparing #2 with #3

Revision #3 was created by phazei phazei on Aug 6, 2010, 8:25:34 AM.

Expanded on behavior example.

Content

[...]
So, basically, it allows you build a list of function calls that can later be executed, in the order they were added. It can save you passing around a lot of object refs and building conditional code, since you can still raise the event, even if it doesn't do anything.

##Behaviors

Behaviors are simply a way of adding methods to an object.
 
 
 
Take this scenario:
 
You have 2 classes: MySuperClass1, MySuperClass2.
 
There might be lots of methods from MySuperClass1 & 2 that you want in some new class, say MyBoringClass. Unfortunately, php does not allow for this:
 
 
```php 
class MyBoringClass extends MySuperClass1, MySuperClass2 {
 
}
 
```
 
This is where behaviors come in.  Instead, you can go:
 
 
```php 
class MyBoringClass extends MySuperClass1 {
 
}
 
 
$classInstance = new MyBoringClass();
 
$classInstance->attachbehavior('uniqueName', new MySuperClass2);
 
```
 
Now $classInstance has all the methods from MySuperClass1 and MySuperClass2.  Since MySuperClass2 is being used as a behavior, it has to extend CBehavior.
 
The only caveat to this is an attached behavior cannot override any class methods of the component it is being attached to.  If a method already exists, if it be from the original class or already added by a previously attached behavior, it will not be overwritten.
 
 
 
In an OO language like Ruby, it's quite possible to start with an completely empty object and simply build its behavior as you go along. Yii provides this behavior with a little magic. The key is that the class you wish to add the behavior from must extend Cbehavior.


```php
class SomeClass extends CBehavior
{
[...]