I need to override & add methods in a model invoked by a controller. I don't want to write anything inside Model class file because it's used by other controllers too. Methods are like pagination()
and find()
, can I do it from inside a controller?
Asked
Active
Viewed 769 times
0

JJJ
- 32,902
- 20
- 89
- 102

duckduckgo
- 1,280
- 1
- 18
- 32
-
Is there a reason why you can't name the methods something else? – JJJ Oct 11 '11 at 07:02
-
sounds to me like a very wild idea... why would one want to add methods to a model object dynamically? – mark Oct 11 '11 at 11:52
-
If you need to use your code in multiple controllers then you should probably be using a component, and rethinking your approach. – Ross Oct 11 '11 at 13:59
-
@mark - i have only one controller using model in different implementation, any change in model file will affect others. – duckduckgo Oct 12 '11 at 06:22
-
@Ross - I have only one controller for searching funtion. – duckduckgo Oct 12 '11 at 06:38
-
@Juhan - Sounds like an option, i can create pagination2() but then will paginationCount2() automatically gets called? – duckduckgo Oct 12 '11 at 06:39
1 Answers
2
CakePHP behaviors are mixins. They add methods to a model, which is what you are looking for.
It sounds like dynamically attaching a behavior to the model would get you the outcome you need.
Looking at Model::__construct()
, I can see that it calls $this->Behaviors->init($this->alias, $this->actsAs);
.
You may be able to call it again after the model has been instantiated to attach different behaviors (ie. $this->MyModel->Behaviors->init('MyModel', array('MyBehavior'));
).
In fact, a closer look reveals that $this->MyModel->Behaviors
is an instance of BehaviorCollection
. As such, you can use the attach() method.

deizel.
- 11,042
- 1
- 39
- 50
-
thanks for useful information, here is the link of similar case to mine http://stackoverflow.com/questions/137006/php-redefine-class-methods-or-class being from java background i was confused. Seems like using Another function or behaviors is the way to go. – duckduckgo Oct 13 '11 at 13:10
-
deizel - can attach behaviors overwrite the methods or it is good for adding new ones? – duckduckgo Oct 13 '11 at 13:12
-
Just tested this locally and I am afraid they are only good for adding methods. If you wish to override methods you should extend the class instead. – deizel. Oct 13 '11 at 13:27