# 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:
~~~
<?php
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Behavior\Timestampable;
class Users extends Model
{
public $id;
public $name;
public $created_at;
public function initialize()
{
$this->addBehavior(
new Timestampable(
[
"beforeCreate" => [
"field" => "created_at",
"format" => "Y-m-d",
]
]
)
);
}
}
~~~
The following built-in behaviors are provided by the framework:
| Name | Description |
| --- | --- |
| Timestampable | Allows to automatically update a model’s attribute saving the datetime when a record is created or updated |
| SoftDelete | Instead 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:
~~~
<?php
use Phalcon\Mvc\Model\Behavior\Timestampable;
public function initialize()
{
$this->addBehavior(
new Timestampable(
[
"beforeCreate" => [
"field" => "created_at",
"format" => "Y-m-d",
]
]
)
);
}
~~~
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](http://php.net/manual/zh/function.date.php), format can also be an anonymous function providing you the free to generate any kind timestamp:
~~~
<?php
use DateTime;
use DateTimeZone;
use Phalcon\Mvc\Model\Behavior\Timestampable;
public function initialize()
{
$this->addBehavior(
new Timestampable(
[
"beforeCreate" => [
"field" => "created_at",
"format" => function () {
$datetime = new Datetime(
new DateTimeZone("Europe/Stockholm")
);
return $datetime->format("Y-m-d H:i:sP");
}
]
]
)
);
}
~~~
If the option ‘format’ is omitted a timestamp using the PHP’s function[time](http://php.net/manual/zh/function.time.php), will be used.
## 軟刪除(SoftDelete)
This behavior can be used in the following way:
~~~
<?php
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Behavior\SoftDelete;
class Users extends Model
{
const DELETED = "D";
const NOT_DELETED = "N";
public $id;
public $name;
public $status;
public function initialize()
{
$this->addBehavior(
new SoftDelete(
[
"field" => "status",
"value" => Users::DELETED,
]
)
);
}
}
~~~
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:
~~~
mysql> select * from users;
+----+---------+--------+
| id | name | status |
+----+---------+--------+
| 1 | Lana | N |
| 2 | Brandon | N |
+----+---------+--------+
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:
~~~
<?php
Users::findFirst(2)->delete();
~~~
The operation will result in the following data in the table:
~~~
mysql> select * from users;
+----+---------+--------+
| id | name | status |
+----+---------+--------+
| 1 | Lana | N |
| 2 | Brandon | D |
+----+---------+--------+
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](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model_BehaviorInterface.html). Also,[Phalcon\\Mvc\\Model\\Behavior](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model_Behavior.html)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:
~~~
<?php
use Phalcon\Mvc\Model\Behavior;
use Phalcon\Mvc\Model\BehaviorInterface;
class Blameable extends Behavior implements BehaviorInterface
{
public function notify($eventType, $model)
{
switch ($eventType) {
case "afterCreate":
case "afterDelete":
case "afterUpdate":
$userName = // ... get the current user from session
// Store in a log the username, event type and primary key
file_put_contents(
"logs/blamable-log.txt",
$userName . " " . $eventType . " " . $model->id
);
break;
default:
/* ignore the rest of events */
}
}
}
~~~
The former is a very simple behavior, but it illustrates how to create a behavior, now let’s add this behavior to a model:
~~~
<?php
use Phalcon\Mvc\Model;
class Profiles extends Model
{
public function initialize()
{
$this->addBehavior(
new Blameable()
);
}
}
~~~
A behavior is also capable of intercepting missing methods on your models:
~~~
<?php
use Phalcon\Tag;
use Phalcon\Mvc\Model\Behavior;
use Phalcon\Mvc\Model\BehaviorInterface;
class Sluggable extends Behavior implements BehaviorInterface
{
public function missingMethod($model, $method, $arguments = [])
{
// If the method is 'getSlug' convert the title
if ($method === "getSlug") {
return Tag::friendlyTitle($model->title);
}
}
}
~~~
Call that method on a model that implements Sluggable returns a SEO friendly title:
~~~
<?php
$title = $post->getSlug();
~~~
## 使用 Traits 實現行為(Using Traits as behaviors)
Starting from PHP 5.4 you can use[Traits](http://php.net/manual/zh/language.oop5.traits.php)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:
~~~
<?php
trait MyTimestampable
{
public function beforeCreate()
{
$this->created_at = date("r");
}
public function beforeUpdate()
{
$this->updated_at = date("r");
}
}
~~~
Then you can use it in your model as follows:
~~~
<?php
use Phalcon\Mvc\Model;
class Products extends Model
{
use MyTimestampable;
}
~~~
- 簡介
- 安裝
- 安裝(installlation)
- XAMPP下的安裝
- WAMP下安裝
- Nginx安裝說明
- Apache安裝說明
- Cherokee 安裝說明
- 使用 PHP 內置 web 服務器
- Phalcon 開發工具
- Linux 系統下使用 Phalcon 開發工具
- Mac OS X 系統下使用 Phalcon 開發工具
- Windows 系統下使用 Phalcon 開發工具
- 教程
- 教程 1:讓我們通過例子來學習
- 教程 2:INVO簡介
- 教程 3: 保護INVO
- 教程4: 使用CRUD
- 教程5: 定制INVO
- 教程 6: V?kuró
- 教程 7:創建簡單的 REST API
- 組件
- 依賴注入與服務定位器
- MVC架構
- 使用控制器
- 使用模型
- 模型關系
- 事件與事件管理器
- Behaviors
- 模型元數據
- 事務管理
- 驗證數據完整性
- Workingwith Models
- Phalcon查詢語言
- 緩存對象關系映射
- 對象文檔映射 ODM
- 使用視圖
- 視圖助手
- 資源文件管理
- Volt 模版引擎
- MVC 應用
- 路由
- 調度控制器
- Micro Applications
- 使用命名空間
- 事件管理器
- Request Environmen
- 返回響應
- Cookie 管理
- 生成 URL 和 路徑
- 閃存消息
- 使用 Session 存儲數據
- 過濾與清理
- 上下文編碼
- 驗證Validation
- 表單_Forms
- 讀取配置
- 分頁 Pagination
- 使用緩存提高性能
- 安全
- 加密與解密 Encryption/Decryption
- 訪問控制列表
- 多語言支持
- 類加載器 Class Autoloader
- 日志記錄_Logging
- 注釋解析器 Annotations Parser
- 命令行應用 Command Line Applications
- Images
- 隊列 Queueing
- 數據庫抽象層
- 國際化
- 數據庫遷移
- 調試應用程序
- 單元測試
- 進階技巧與延伸閱讀
- 提高性能:下一步該做什么?
- Dependency Injection Explained
- Understanding How Phalcon Applications Work
- Api
- Abstract class Phalcon\Acl