Behaviour is shared conducts which is used by the models to reuse the code. The ORM provides an API to implement behaviours in the models. To implement behaviour we have alternative such as events and callbacks which increases the efficiency of behaviours.
Build-in behaviours are as follows:
Name | Description |
---|---|
Timestampable | It allows to automatically updates 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. |
Implementation
It implements Timestampable a pre-defined behaviour which consists of many options for single event or for complete event.
<?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',
]
]
)
);
}
}
Now, creating array option for ‘format’ using php function ‘time’:
<?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('India/Delhi')
);
return $datetime->format('Y-m-d H:i:sP');
}
]
]
)
);
}
Leave a Reply