4

What exactly is a CakePHP behavior? Where and how should I use it?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
D555
  • 1,704
  • 6
  • 26
  • 48
  • See the [behaviors chapter](http://book.cakephp.org/2.0/en/models/behaviors.html) in the cookbook. – dhofstet Aug 30 '13 at 06:55
  • There is an entire chapter (per comment above) on what Behaviors are, when/why to use them..etc. This is not the place for a question like this. – Dave Aug 30 '13 at 18:56
  • Sometimes you are looking for a different approache. I think the question is valid. Davit answer helped me a lot. Just remember to accept his answer. – Bagata Jul 04 '14 at 12:55

2 Answers2

13

Behaviors in CakePHP are living on the model side of the framework. Since we all prefer to create a reusable and dry logic, behaviors are provided by CakePHP to get away from 'ugly' and extra code. Behaviors "change" the way models behaves, enforcing it to "act as" something.

You can think of them, that they are for models, what components are for controllers and helpers are for views. Behaviors help you make your code more abstract, not to mention that they can be shared across different models.

When you force a model to behave as something or as some things, you just use functions of that behavior(s). Of course later you can take away or perhaps temporarily force a model to forget about this or that behavior.

There lots of other stuff that you can ask models about behaviors, for example check if model behaves like this or that, if not to behave.

Generally, you tell a model to behave using public $actAs = array(); statement, but you can do it by $this->ModelName->Behaviors->load('BehaviorName') too.

You use them in models of course. Unless you implement your own behaviors rather than use tons of them available at the bakery, you load them and use them as if models already supported such kinds of functions.

Davit
  • 1,394
  • 5
  • 21
  • 47
  • Thank you so much Dachi for your kind explanation. Can you kindly give one general practical example where I should use them? – D555 Aug 30 '13 at 04:48
  • You're very much welcome. Well, I went over some websites and I think http://www.cakephpexample.com/cakephp-basics/cakephp-tree-behavior-example/ gives a reasonable case where use of behaviors is very efficient. Good luck – Davit Aug 30 '13 at 04:56
1

Behaviors in CakePHP are living on the model side of the framework. Since we all prefer to create a reusable and dry logic, behaviors are provided by CakePHP to get away from 'ugly' and extra code. Behaviors "change" the way models behaves, enforcing it to "act as" something.