Scriptbaker
SCRIPTBAKERAI & Software Engineering
Yii

Yii 1.1: Behaviors & Events

Learn how Yii 1.1 behaviors and events work, how to attach reusable functionality to components, handle application events, and use behaviors with Active Record models through practical PHP examples

· 5 min read · By Tahir Yasin

Yii 1.1: Behaviors & Events

Yii 1.1 provides two powerful mechanisms for extending component functionality without modifying the original class: behaviors and events. Both are built around Yii's component system and can help you add reusable functionality, respond to application events, and reduce unnecessary class inheritance.

Understanding the difference between behaviors and events is important when working with existing Yii 1.1 applications, especially legacy projects where you need to extend functionality without changing framework or third-party source code.

In simple terms, an event lets you run one or more handlers when something happens, while a behavior lets you attach additional methods and functionality to an existing component.

What Are Behaviors and Events in Yii 1.1?

Both behaviors and events are features of Yii's CComponent architecture. Yii components can have properties, events, and behaviors, allowing functionality to be composed without relying exclusively on traditional inheritance.

The Yii 1.1 API defines CComponent as the base class for Yii components. It provides methods such as attachBehavior(), attachEventHandler(), raiseEvent(), detachBehavior(), and detachEventHandler(). :contentReference\[oaicite:1]{index=1}

Yii 1.1 Events

An event allows an object to notify other parts of an application that something has happened. Instead of modifying the original class or extending it simply to insert additional logic, you can attach one or more event handlers.

For example, the Yii application exposes lifecycle events such as onBeginRequest, onEndRequest, onException, and onError. The application lifecycle raises these events at specific points during request processing. :contentReference\[oaicite:2]{index=2}

Creating an Event Handler

An event handler is a PHP callback that receives an event object. In the traditional Yii 1.1 event model, the handler receives a CEvent object or an object derived from it.

$component->onSomethingHappened = array($object, 'handleEvent');

The handler can then be defined as:

public function handleEvent($event){    // Handle the event here.}

Yii also supports anonymous functions as event handlers when running on PHP versions that support closures. The original Yii documentation notes this support from Yii 1.0.10 onward. :contentReference\[oaicite:3]{index=3}

Attaching Multiple Event Handlers

More than one handler can be attached to the same event. When the event is raised, Yii invokes the attached handlers in the order in which they were added.

$testComponent->onSomethingHappened = array(    new FirstHandler(),    'handleEvent');$testComponent->onSomethingHappened = array(    new SecondHandler(),    'handleEvent');

A handler can also stop subsequent handlers from being executed by setting the event's handled property to true, where supported by the event processing logic. :contentReference\[oaicite:4]{index=4}

Raising an Event

A component can raise an event by passing an event object to the corresponding event method:

$testComponent->onSomethingHappened(new CEvent($this));

The event can also be raised without explicitly providing a sender:

$testComponent->onSomethingHappened(new CEvent());

Internally, Yii's component system provides raiseEvent() for raising events. :contentReference\[oaicite:5]{index=5}

Example: Application Request Events

Yii applications provide request lifecycle events that can be used to execute logic before or after request processing.

Yii::app()->onBeginRequest = function($event){    // Code executed before the request is processed.};Yii::app()->onEndRequest = function($event){    // Code executed after the request is processed.};

For example, application-level request events can be used for tasks such as request initialization, logging, response processing, or other cross-cutting functionality. CApplication defines onBeginRequest as being raised immediately before request processing and onEndRequest immediately after it. :contentReference\[oaicite:6]{index=6}

Yii 1.1 Behaviors

A behavior is a reusable object that can be attached to a Yii component to provide additional methods and functionality.

Yii describes behaviors as a way for a component to inherit methods from one or more behavior objects. This provides a form of composition that can be used when traditional single inheritance would not be sufficient. :contentReference\[oaicite:7]{index=7}

A behavior normally extends CBehavior. Yii also provides specialized behavior base classes such as CModelBehavior and CActiveRecordBehavior for model-related functionality. :contentReference\[oaicite:8]{index=8}

Why Use a Behavior?

PHP class inheritance allows a class to extend one parent class. If you have reusable functionality that does not naturally belong in the inheritance hierarchy, a behavior can be a better approach.

For example, suppose you have several components that need a common helper method. Instead of copying that method into every class, you can place it in a behavior and attach that behavior to the required components.

Creating a Custom Behavior

A simple Yii behavior can extend CBehavior and define one or more public methods:

class MathBehavior extends CBehavior{    public function add($x, $y)    {        return $x + $y;    }}

The behavior can then be attached to a component:

$testComponent = new TestComponent();$testComponent->attachBehavior(    'math',    new MathBehavior());$result = $testComponent->add(2, 5);

In this example, add() is defined by the behavior rather than by TestComponent, but it can be called through the component after the behavior has been attached.

Attaching a Behavior by Configuration

Yii 1.1 also supports attaching behaviors through configuration. This is commonly useful for application components.

return array(    'components' => array(        'db' => array(            'class' => 'CDbConnection',            'behaviors' => array(                'myBehavior' => array(                    'class' => 'ext.myBehavior.MyBehavior',                    'property1' => 'value1',                    'property2' => 'value2',                ),            ),        ),    ),);

Yii's official extension guide documents this configuration-based approach and notes that behaviors can be attached to application components through the component's behaviors property. :contentReference\[oaicite:9]{index=9}

Behaviors in Controllers and Models

Controllers, form models, and Active Record models commonly declare behaviors by overriding their behaviors() method.

public function behaviors(){    return array(        'myBehavior' => array(            'class' => 'ext.myBehavior.MyBehavior',        ),    );}

CController and CActiveRecord both expose behavior-related functionality through the Yii component architecture. :contentReference\[oaicite:10]{index=10}

Behavior vs. Event: What's the Difference?

Although behaviors and events are often used together, they solve different problems.

Feature Behavior Event
Primary purpose Add reusable functionality to a component React when something happens
Typical use Add methods or reusable logic Run callbacks at a specific point
Common base class CBehavior CEvent describes event data
Can have multiple instances? Yes Yes, multiple handlers can be attached
Example Add reusable model functionality Run code before or after an operation

Behaviors and Events Can Work Together

One useful pattern is to create a behavior that attaches event handlers to the component it is attached to. This allows reusable functionality to respond automatically to the component's lifecycle.

For example, a model behavior can listen for model events and perform common logic before or after saving.

class AuditBehavior extends CActiveRecordBehavior{    public function events()    {        return array(            'onBeforeSave' => 'beforeSave',            'onAfterSave' => 'afterSave',        );    }    public function beforeSave($event)    {        // Add reusable logic before saving.    }    public function afterSave($event)    {        // Add reusable logic after saving.    }}

This approach is especially useful when the same behavior needs to be reused by multiple Active Record models.

Common Yii 1.1 Behavior Methods

Yii's CComponent API includes several methods for managing behaviors:

  • attachBehavior() — attaches a behavior to a component.
  • attachBehaviors() — attaches multiple behaviors.
  • detachBehavior() — removes an attached behavior.
  • detachBehaviors() — removes all attached behaviors.
  • enableBehavior() — enables a behavior.
  • disableBehavior() — disables a behavior.
  • asa() — retrieves a named behavior.

These methods are part of Yii's component API and are available to classes derived from CComponent. :contentReference\[oaicite:11]{index=11}

Common Yii 1.1 Event Methods

The component system also provides methods for managing event handlers:

  • attachEventHandler() — attaches an event handler.
  • detachEventHandler() — removes an event handler.
  • getEventHandlers() — retrieves handlers attached to an event.
  • hasEvent() — checks whether an event exists.
  • hasEventHandler() — checks whether an event has handlers.
  • raiseEvent() — raises an event.

These APIs are documented as part of CComponent. :contentReference\[oaicite:12]{index=12}

When Should You Use Behaviors?

Behaviors are useful when you need to:

  • Reuse the same functionality across multiple components.
  • Add methods without changing the original component class.
  • Share functionality between models or Active Record classes.
  • Keep reusable logic separate from the classes that use it.
  • Avoid creating unnecessary subclasses for small pieces of reusable functionality.

When Should You Use Events?

Events are useful when you need to:

  • Run code when a particular action or lifecycle event occurs.
  • Add functionality without modifying the original class.
  • Allow multiple independent parts of an application to react to the same event.
  • Decouple the code that triggers an action from the code that responds to it.
  • Hook into application, controller, model, or component lifecycle events.

Important Considerations for Legacy Yii 1.1 Projects

Yii 1.1 is commonly encountered today in existing or legacy PHP applications. When maintaining such applications, behaviors and events can be useful because they allow developers to extend functionality while minimizing changes to established classes.

Before introducing a new behavior or event handler, check the component's existing methods and events. A behavior should not be treated as a replacement for every form of inheritance, and event handlers should be kept focused so that application flow remains understandable.

It is also important to distinguish Yii 1.1's architecture from modern PHP frameworks. Yii 1.1 uses its own component, behavior, and event mechanisms, so examples written for newer frameworks should not automatically be assumed to work in Yii 1.1.

Frequently Asked Questions

What is a behavior in Yii 1.1?

A behavior is a reusable object that can be attached to a Yii component to add methods and functionality. Yii's CBehavior class provides the standard base for behavior implementations. :contentReference\[oaicite:13]{index=13}

What is an event in Yii 1.1?

An event allows a component to notify attached handlers when a particular action or lifecycle point occurs. Multiple handlers can be attached to the same event.

What is CComponent in Yii 1.1?

CComponent is the base class for Yii components. It provides the foundation for properties, events, and behaviors, including methods for attaching and detaching event handlers and behaviors. :contentReference\[oaicite:14]{index=14}

What is CBehavior in Yii 1.1?

CBehavior is Yii's convenient base class for creating behaviors. Custom behavior classes can extend it and define reusable methods that become available through the component to which the behavior is attached. :contentReference\[oaicite:15]{index=15}

Can multiple behaviors be attached to one component?

Yes. Yii components can have multiple behaviors attached to them. Each behavior is identified by a unique name when it is attached. :contentReference\[oaicite:16]{index=16}

Can multiple event handlers be attached to one event?

Yes. Yii supports multiple handlers for an event, and the handlers are invoked in the order in which they were attached. :contentReference\[oaicite:17]{index=17}

Can a behavior override an existing component method?

No. A behavior does not replace an existing method on the component. If the component already provides a method with the same name, the existing component method takes precedence.

Can behaviors be used with Active Record models?

Yes. Yii provides model-specific behavior classes, including CModelBehavior and CActiveRecordBehavior, for adding reusable functionality to models and Active Record classes. :contentReference\[oaicite:18]{index=18}

How do I attach a behavior to a Yii component?

You can use attachBehavior() directly:

$component->attachBehavior(    'myBehavior',    new MyBehavior());

Yii also supports attaching behaviors through configuration and through the behaviors() method on classes such as controllers and Active Record models. :contentReference\[oaicite:19]{index=19}

How do I attach an event handler in Yii 1.1?

You can assign a PHP callback to the event:

$component->onSomethingHappened = array(    $object,    'handleEvent');

You can also use attachEventHandler() when you want to explicitly attach a handler through the component API. :contentReference\[oaicite:20]{index=20}

What is the difference between a behavior and an event?

A behavior adds reusable functionality to a component, while an event provides a way for other code to respond when something happens. In practice, a behavior can also register event handlers, allowing the two mechanisms to work together.

Conclusion

Yii 1.1 behaviors and events provide a flexible way to extend applications without constantly modifying or subclassing existing components. Behaviors are primarily about adding reusable functionality, while events are primarily about responding to actions or lifecycle points.

Once you understand CComponent, CBehavior, CEvent, behavior attachment, and event handlers, you can use these mechanisms to maintain and extend Yii 1.1 applications with less duplication and fewer changes to existing classes.

Official Yii 1.1 References

Last updated:

Work with Scriptbaker

Let's talk about your project

Whether you're extending an existing platform, modernising legacy code, or planning something new, our engineers can help. Tell us what you're working on and we'll explore a practical technical solution together.