0

我想从我的模型中指定一个字段的输出,所以我添加了一个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);
    }

?>

这似乎不起作用。当我执行 find all 时,这个过滤器似乎被命中了两次。第一次,$entity包含一个count()结果,只有在第二次命中时,它才包含该Records对象。

我究竟做错了什么?我该如何改变它,以便<?= $tag->created; ?>在我的视图中简单地按照我想要的方式格式化日期?从本质上讲,这需要是某种“后过滤器”。

编辑

如果我能找到一种访问当前模型实体对象的方法(不是完整的命名空间路径,$self 包含它),我可能可以解决我的问题。

4

2 回答 2

4

Regardless of a small fix for your after find filter, I would do it differently.

Every time you'll do a find, you'll override your date format, even if you don't want to display it, but only do a business logic like comparing dates etc ...

Since you want to format your output only in your views (we are not talking about formatting on the fly json responses for an API, etc.), why not using a helper method ?

An other way is to add an instance method in your model (or a BaseModel), called created_at(). Then, you will call it from a view with <?= $entity->created_at() ?> You can still force a format fetched from your $_schema, or pass it as a param, etc ...

A helper seems cleaner as we are talking about presenting data in your views.

于 2012-03-27T23:46:33.857 回答
0

我正在阅读 OP 的问题,因为 find 过滤器执行了两次。如果这是正确的,那么为什么不检查 $entity 是否包含记录集呢?

于 2012-03-27T19:36:02.463 回答