MainelyDesign.com Blog

Changing the Order Sequence of CakePHP Behaviors

Posted on 02/25/2010 at 07:20 am by Kevin Wentworth
Viewed 8,548 times | 0 comments

For reasons too long to explain in this post, I have two behaviors that are run on the same pieces of data (a translate behavior and a settings import/export behavior).  One behavior is attached to the model using var $actsAs, while the other behavior is attached dynamically, during runtime using $this->attachBehavior();.  I needed the "hardcoded" behavior to run after the dynamically attached behavior.  Here's what I did:

Changing the Order of CakePHP Behaviors via $actsAs

First, the simplest way to change the order of how behaviors are run (and the sequence that data will be manipulated) is to order the Behaviors in the appropriate way using the $actsAs variable.  If you can't do it this way, then you need to dynamically change the order of attached behaviors.

Changing the Order of Attached Behaviors from the Controller

Because I couldn't change the order in actsAs, I was resigned to changing the order that the behaviors are attached.  I started trying to manipulate the $this->ModelName->Behaviors object, but took a step back and realized an easy solution (the way CakePHP developers intended): detach the "hardcoded" behavior and re-attach it after the dyanmically attached behavior.  Simple, and it works:

  1. $this->Form->Behaviors->detach('Avsettings');   //want to run after translate behaviors (depends on order in Behaviors)
  2. $this->Form->attachTranslate();     //attaches translate behavior dynamically/at runtime
  3. $this->Form->Behaviors->attach('Avsettings');   //now it will run after translate behaviors

The CakePHP manual has a great page that describes dynamically attaching behaviors as well as enabling and disabling behaviors.

Cheers,
-Kevin Wentworth

Bookmark and Share

Tags for Changing the Order Sequence of CakePHP Behaviors

Cakephp | Web Programming | Tutorial | Usage | Behaviors | Example

Comments for this Posting

No comments. Be the first to post a reply.

Sorry, comments are closed for this posting.

Please Email Kevin if you have any questions. Thanks!

Meet Site Avenger - Hosted Content Management System

Powered By: Site Avenger | Site Production: Saco Design