Model Behaviors

Behaviors are shared conducts 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:

  1. <?php
  2. use Phalcon\Mvc\Model;
  3. use Phalcon\Mvc\Model\Behavior\Timestampable;
  4. class Users extends Model
  5. {
  6. public $id;
  7. public $name;
  8. public $created_at;
  9. public function initialize()
  10. {
  11. $this->addBehavior(
  12. new Timestampable(
  13. [
  14. "beforeCreate" => [
  15. "field" => "created_at",
  16. "format" => "Y-m-d",
  17. ]
  18. ]
  19. )
  20. );
  21. }
  22. }

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

NameDescription
TimestampableAllows to automatically update a model’s attribute saving the datetime when a record is created or updated
SoftDeleteInstead of permanently delete a record it marks the record as deleted changing the value of a flag column

生成时间戳(Timestampable)

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

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

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. }

If the option ‘format’ is omitted a timestamp using the PHP’s function time, will be used.

软删除(SoftDelete)

This behavior can be used in the following way:

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

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:

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

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.

创建行为(Creating your own behaviors)

The ORM provides an API to create your own behaviors. A behavior must be a class implementing the Phalcon\Mvc\Model\BehaviorInterface. Also, Phalcon\Mvc\Model\Behavior provides most of the methods needed to ease the implementation of behaviors.

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

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

  1. <?php
  2. use Phalcon\Mvc\Model;
  3. class Profiles extends Model
  4. {
  5. public function initialize()
  6. {
  7. $this->addBehavior(
  8. new Blameable()
  9. );
  10. }
  11. }

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

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

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

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

使用 Traits 实现行为(Using Traits as behaviors)

Starting from PHP 5.4 you can use Traits 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");
  11. }
  12. }

Then you can use it in your model as follows:

  1. <?php
  2. use Phalcon\Mvc\Model;
  3. class Products extends Model
  4. {
  5. use MyTimestampable;
  6. }