views:

27

answers:

2

I have a Behavior attached to a Model that should behave differently depending on some property of the model. Example:

class Airplane extends AppModel {
    var $actsAs = array('Flying');
}

class FlyingBehavior extends ModelBehavior {
    function flightTime(&$Model, $distance) {
        return $distance / $this->speed;
    }
}

Initially I thought I setting it like

class Airplane extends AppModel {
    var $actsAs = array('Flying' => 
                      array('speed' => SOMENUM)
                  );
}

class FlyingBehavior extends ModelBehavior {
    function setup(&$Model, $settings) {
        $this->speed = $settings['speed'];
    }

    function flightTime(&$Model, $distance) {
        return $distance / $this->speed;
    }
}

But I don't know how to make this work, because I'd need to fetch the speed column from each Airplane record. How should I do this?

+1  A: 

In your flightTime() method, you have access to your originating model. You can call any property or method on that model (or any of its super/parent classes) as $Model->find( ... ) or whatnot. You can use that technique to retrieve any information specific to the model, but ensure that the same information is available to all models to whom the behavior is attached (or at least check that the property/method is available).

Rob Wilkerson
Not a good solution because it forces me to query twice for data that I already have.
pessimopoppotamus
Where do you already have it? You have complete access to the model. If it's stored as a property of the model, you should be able to just grab it.
Rob Wilkerson
A: 

I solved the problem by adding code to the afterFind() callback; setting a property in the Model.

I then just need to access it via$Model->property from the Behavior. This should be possible without having to meddle with afterFind() but unfortunately I didn't find the way to do it.

pessimopoppotamus