我想在模型中指定字段的输出,因此我向date
添加了$_schema
键:
models/Tags.php
<?php
protected $_schema = array(
'id' => array('type' => 'integer', 'key' => 'primary'),
'title' => array('type' => 'string'),
'created' => array('type' => 'integer', 'date' => 'F jS, Y - g:i a'),
'modified' => array('type' => 'integer')
);
?>
我将时间作为无符号整数存储在db(time()
的输出)中。
我希望我的基本模型格式化任何具有date
键输出的字段。我认为最好的地方就是在find
:
extensions/data/Model.php
<?php
static::applyFilter('find', function($self, $params, $chain) {
$schema = $self::schema();
$entity = $chain->next($self, $params, $chain);
foreach ($schema as $field => $options) {
if (array_key_exists('date', $options)) {
//format as a date
$params['data'][$field] = $entity->formatDate($field, $options['date']);
}
}
return $entity;
});
public function formatdate($entity, $field, $format, $timezone = 'Asia/Colombo') {
$dt = new \DateTime();
$tz = new \DateTimeZone($timezone);
$dt->setTimestamp($entity->$field);
$dt->setTimezone($tz);
return $dt->format($format);
}
?>
这似乎不起作用。当我执行全部查找时,此过滤器似乎被击中两次。第一次,$entity
包含结果count()
,仅在第二次点击时包含Records
对象。
我做错了什么?如何改变这一点,以便在我的视图中简单地执行<?= $tag->created; ?>
将按照我想要的方式格式化日期?从本质上讲,这需要在过滤器之后进行排序。
修改
如果我能找到一种方法来访问当前模型实体对象(不是完整的命名空间路径,$ self包含它),我可以解决我的问题。
答案 0 :(得分:4)
无论您的后找到过滤器有什么小修复,我都会采用不同的方式。
每次你进行查找,你都会覆盖你的日期格式,即使你不想显示它,但只做一个像比较日期等业务逻辑......
由于您只想在视图中格式化输出 (我们不是在讨论API的动态json响应格式等),为什么不使用辅助方法?
另一种方法是在模型(或BaseModel)中添加一个名为created_at()
的实例方法。然后,您将从<?= $entity->created_at() ?>
的视图中调用它
您仍然可以强制从$ _schema获取格式,或者将其作为参数传递等...
当我们谈论在您的视图中显示数据时,助手似乎更清晰。
答案 1 :(得分:0)
我正在阅读OP的问题,因为查找过滤器执行了两次。如果这是正确的,那么为什么不检查$实体是否包含记录集?