0

OOP 菜鸟在这里。我想利用 CakePHP 2.3 的短日期方法,以便在适当的时候获得“今天”或“昨天”,同时在输出不是“今天”或“昨天”时更改日期的格式。

示例视图:echo $this->Time->niceShort($user['User']['last_invited_on'];.

我在lib/Cake/Utility/CakeTime.php(CakeTimeHelper使用该CakeTime实用程序)中找到了以下内容:

class CakeTime {

/**
 * The format to use when formatting a time using `CakeTime::nice()`
 *
 * The format should use the locale strings as defined in the PHP docs under
 * `strftime` (http://php.net/manual/en/function.strftime.php)
 *
 * @var string
 * @see CakeTime::format()
 */
    public static $niceFormat = '%a, %b %eS %Y, %H:%M';

/**
 * The format to use when formatting a time using `CakeTime::timeAgoInWords()`
 * and the difference is more than `CakeTime::$wordEnd`
 *
 * @var string
 * @see CakeTime::timeAgoInWords()
 */
    public static $wordFormat = 'j/n/y';

/**
 * The format to use when formatting a time using `CakeTime::niceShort()`
 * and the difference is between 3 and 7 days
 *
 * @var string
 * @see CakeTime::niceShort()
 */
    public static $niceShortFormat = '%B %d, %H:%M';

我可以以某种方式覆盖此类的公共属性,以便Time->niceShort在视图中使用时更改输出的日期格式吗?(这是“猴子补丁”吗?)如果是这样,什么是好的/干净的方法?

或者我应该编写一个新的扩展类,CakeTime这是否意味着必须更改$this->Time$this->MyNewSpiffingCustomisedTimein 视图(我不想这样做,因为其他习惯使用 Cake's 的Time人正在从事该项目)?我想知道这是否只是为了更改属性而过大。

4

2 回答 2

0

为什么不扩展助手?

在 中创建一个类app/View/Helper/myTimeHelper.php。在那里添加对旧类的引用,您将被扩展为:

App::uses('TimeHelper', 'View/Helper');

class myTimeHelper extends TimeHelper {
    public function niceShort(<whatever input the original is getting>) {
        // your new logic for the things you want to change
        // and/or a return TimeHelper::niceShort(<whatever>) for the cases that are
        //fine as they are. If you don't need that then you can remove App::uses.
}

最后,您可以将助手导入myTime

public $helpers = array('myTime');

甚至将默认值更改Time为调用myTime,这样您就无需在已编写的代码中更改任何其他内容:

public $helpers = array('Time' => array('className' => 'myTime'));
于 2013-09-18T16:24:35.273 回答
0

旧: 不需要,你可以比较:

if (date('Y-m-d') != $date && date('Y-m-d', strtotime('-1 day')) != $date) {
    //something
    echo $this->Time->niceShort($date);
    //something
}

Y-m-d无论您的日期格式是什么,即Y-m-d H:i:s

新: 正确的方法是为date('format', strtotime($date));. CakePHP 包装器被定义为$this->Time->format('format', $date);并调用我列出的前面的 php 函数。

如果您计划在任何时候升级,则不应个性化基本代码。仍然调用 $this->Time 并扩展基本代码的唯一方法(我现在能想到的)是实现一个名为Time并包含在您的$helper和/或$component成员变量中的插件Time.mySpiffyTimeThingo,其中 mySpiffyTimeThingo 是组件的名称或帮手。这些可以扩展/覆盖当前的 CakePHP CakeTime 函数。

于 2013-09-18T12:36:42.437 回答