Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to call Custom Behavior?

Hi, I am struggling to make a custom behavior and to call it from models.

My idea is to put time-formatting functions in a behavior so it can be called from other models.

But I have no idea about how to call a method of the behavior.

In the reference about "Blameable behavior"(http://blog.phalconphp.com/post/47652831003/tutorial-creating-a-blameable-behavior-with-phalcon), for example, it says you are supposed to call behavior's method with Validation Events like beforeCreate. But I want to use Behavior when finding

I searched out the usage of Behavior, and found SoftDelete, and Timestampable Behavior, which are also used with Validation Events.

Is there a diffferent way to access Behavior? Or can i create a custom event to call from any lines you like?

I am wondering Behavior is only available with Valication Events in PhalconPHP, not like cakephp that provides a flexible usage of Behavior.

Hope you have an answer

Hi, your behavior can be linked to any of existing model events via Phalcon\Mvc\Model\Behavior::notify() method. List of model events is here ->http://phalcon-documentacion-en-espanol.readthedocs.org/en/latest/reference/models.html#events-and-events-manager .

About find, i am not sure there is event defined which you are looking for, perhaps you could override find method andset events yourself, something like beforeFind and afterFind, altho i havent tryed this approach myself.

Thanks a lot, digitronac.

Things are getting clear for me with your comment.

so our current conclusion is , behavior is mainly used for events on the list of http://phalcon-documentacion-en-espanol.readthedocs.org/en/latest/reference/models.html#events-and-events-manager, and if you want to use behavior in other situations in a model, you need additional implementation.



53.2k
Accepted
answer

There is an afterFetch event you could tie in to. You could put your time formatting code in the subsequent afterFetch() method.

hi, quasipickle

That's the answer i was searching.

Thank you so much.

I finally decided to use trait as a behavior, which give me so much of flexibility as cakephp or Concern of RoR

(trait function is only availalbe over php 5.4)