日期时间格式化行为
借鉴之前文章的思路,我做了一个行为来格式化日期和时间字段。
我从 Rikkin 的文章中借鉴了思路:https://bakery.cakephp.com.cn/articles/rikkin/2012/01/26/formatos_de_fechas
感谢他,我只是把他的想法放进了一个行为中。
以下是代码:(粘贴在这里:https://bin.cakephp.org/saved/72238)
<?php
class DatetimeFormatterBehavior extends ModelBehavior {
private $__defaultSettings = array(
'date_format' => '%d/%m/%Y',
'date_suffix' => '_d',
'datetime_suffix' => '_dt',
'datetime_format' => '%d/%m/%Y %H:%i:%s',
'fields' => true,
);
function setup(&$model, $config = array()) {
$this->settings[$model->alias] = $config + $this->__defaultSettings;
$this->addDefaultVirtualFields($model);
}
function addDefaultVirtualFields($model) {
extract($this->settings[$model->alias], EXTR_SKIP);
$colTypes = $model->getColumnTypes();
foreach($colTypes as $field => $type){
if($fields === true || in_array($field, $fields)){
if($type === 'date' || $type === 'datetime'){
$model->virtualFields[$field . $date_suffix] = "date_format($model->alias.$field, '" . $date_format . "')";
$model->virtualFields[$field . $datetime_suffix] = "date_format($model->alias.$field, '" . $datetime_format . "')";
}
}
}
}
}
// Usage:
class User extends AppModel {
var $actsAs = array('DatetimeFormatter');
}
// Test (take a look to output):
debug($this->User->find('first'));