Model Behaviors


    Behaviors are shared constructs that several models may adopt in order to re-use code. The ORM provides an API to implement behaviors in your models. Also, you can use the events and callbacks as seen before as an alternative to implement Behaviors with more freedom.

    A behavior must be added in the model initializer, a model can have zero or more behaviors:

    The following built-in behaviors are provided by the framework:

    This behavior receives an array of options, the first level key must be an event name indicating when the column must be assigned:

    1. use Phalcon\Mvc\Model\Behavior\Timestampable;
    2. public function initialize()
    3. {
    4. $this->addBehavior(
    5. new Timestampable(
    6. [
    7. 'beforeCreate' => [
    8. 'field' => 'created_at',
    9. 'format' => 'Y-m-d',
    10. ],
    11. ]
    12. )
    13. );
    14. }

    Each event can have its own options, field is the name of the column that must be updated, if format is a string it will be used as format of the PHP’s function date, format can also be an anonymous function providing you the free to generate any kind timestamp:

    1. <?php
    2. use DateTime;
    3. use DateTimeZone;
    4. use Phalcon\Mvc\Model\Behavior\Timestampable;
    5. public function initialize()
    6. {
    7. $this->addBehavior(
    8. new Timestampable(
    9. [
    10. 'beforeCreate' => [
    11. 'field' => 'created_at',
    12. 'format' => function () {
    13. $datetime = new Datetime(
    14. new DateTimeZone('Europe/Stockholm')
    15. );
    16. return $datetime->format('Y-m-d H:i:sP');
    17. },
    18. ],
    19. ]
    20. )
    21. );
    22. }

    This behavior can be used as follows:

    1. <?php
    2. use Phalcon\Mvc\Model;
    3. use Phalcon\Mvc\Model\Behavior\SoftDelete;
    4. {
    5. const DELETED = 'D';
    6. const NOT_DELETED = 'N';
    7. public $id;
    8. public $name;
    9. public $status;
    10. public function initialize()
    11. {
    12. $this->addBehavior(
    13. new SoftDelete(
    14. [
    15. 'field' => 'status',
    16. 'value' => Users::DELETED,
    17. ]
    18. )
    19. );
    20. }
    21. }

    This behavior accepts two options: field and value, field determines what field must be updated and value the value to be deleted. Let’s pretend the table users has the following data:

    If we delete any of the two records the status will be updated instead of delete the record:

    1. <?php
    2. Users::findFirst(2)->delete();

    The operation will result in the following data in the table:

    1. mysql> select * from users;
    2. +----+---------+--------+
    3. | id | name | status |
    4. +----+---------+--------+
    5. | 1 | Lana | N |
    6. | 2 | Brandon | D |
    7. +----+---------+--------+
    8. 2 rows in set (0.01 sec)

    Note that you need to specify the deleted condition in your queries to effectively ignore them as deleted records, this behavior doesn’t support that.

    The following behavior is an example, it implements the Blameable behavior which helps identify the user that is performed operations over a model:

    1. <?php
    2. use Phalcon\Mvc\ModelInterface;
    3. use Phalcon\Mvc\Model\Behavior;
    4. class Blameable extends Behavior
    5. {
    6. public function notify(string $eventType, ModelInterface $model)
    7. {
    8. switch ($eventType) {
    9. case 'afterCreate':
    10. case 'afterDelete':
    11. $userName = // ... get the current user from session
    12. // Store in a log the username, event type and primary key
    13. file_put_contents(
    14. 'logs/blamable-log.txt',
    15. $userName . ' ' . $eventType . ' ' . $model->id
    16. );
    17. break;
    18. default:
    19. /* ignore the rest of events */
    20. }
    21. }
    22. }

    The former is a very simple behavior, but it illustrates how to create a behavior, now let’s add this behavior to a model:

    A behavior is also capable of intercepting missing methods on your models:

    1. <?php
    2. use Phalcon\Tag;
    3. use Phalcon\Mvc\ModelInterface;
    4. use Phalcon\Mvc\Model\Behavior;
    5. use Phalcon\Mvc\Model\BehaviorInterface;
    6. class Sluggable extends Behavior
    7. {
    8. public function missingMethod(string $model, ModelInterface $method, $arguments = [])
    9. {
    10. // If the method is 'getSlug' convert the title
    11. if ($method === 'getSlug') {
    12. return Tag::friendlyTitle($model->title);
    13. }
    14. }
    15. }

    Call that method on a model that implements Sluggable returns a SEO friendly title:

    1. <?php
    2. $title = $post->getSlug();

    You can use to re-use code in your classes, this is another way to implement custom behaviors. The following trait implements a simple version of the Timestampable behavior:

    1. <?php
    2. trait MyTimestampable
    3. {
    4. public function beforeCreate()
    5. {
    6. $this->created_at = date('r');
    7. }
    8. public function beforeUpdate()
    9. {
    10. $this->updated_at = date('r');