tags:

views:

53

answers:

1

Right now I have several methods in my model which all fetch the same object at their beginning (the model's parent class). I would like to do this automatically and execute some code beforehand.

I would like to say "execute fetchParent() before you call the methods getParentId(), getParentTable() and mayChange()".

It it not sufficient to set this parent-object at initialization, or as a class variable, as the parent can change at runtime.

A: 

Depending on the meaning of "some methods", you may be able to use Cake's native callbacks. More on those at http://book.cakephp.org/view/76/Callback-Methods. It seems more likely, though, that you want to tap into common functionality for custom methods. If that's the case, then what I've done is create custom callbacks. To do so, create a custom callback in the desired model/s. Then, in AppModel::your_method(), test for the existence of that method name and, if it exists, execute it.

Here's some sample code that I've written in the past:

# In AppModel::your_method()
if ( method_exists ( $model, 'your_custom_callback' ) ) {
  $model->your_custom_callback ( $model );
}

# In YourModel
public function your_custom_callback ( $model ) {
  /** Your custom code */
}

You didn't provide much detail so I don't know whether this will meet your needs exactly, but maybe it will at least provide a starting point.

Rob Wilkerson
Thank you for your answer, but I want to configure the methods which should executes callbacks *outside of those methods*. I've added detail to my question.
blinry
I think this method will still work for you. If you can provide the models in which the methods you reference exist, I'll try to update my answer using the specifics of your situation.
Rob Wilkerson