更改CakePHP的格式';s CakeTime方法
哦,这里没有。我想利用CakePHP 2.3的短日期方法,以便在适当的时候获得“今天”或“昨天”,同时在输出不是“今天”或“昨天”时更改日期的格式 示例视图:更改CakePHP的格式';s CakeTime方法,php,cakephp,datetime,overriding,Php,Cakephp,Datetime,Overriding,哦,这里没有。我想利用CakePHP 2.3的短日期方法,以便在适当的时候获得“今天”或“昨天”,同时在输出不是“今天”或“昨天”时更改日期的格式 示例视图:echo$this->Time->niceShort($user['user']['last\u invested\u on']; 我在lib/Cake/Utility/CakeTime.php中发现了以下内容(Cake的TimeHelper使用CakeTime实用程序): 每当视图中使用Time->niceShort时,我是否可以重写此类
echo$this->Time->niceShort($user['user']['last\u invested\u on'];
我在lib/Cake/Utility/CakeTime.php
中发现了以下内容(Cake的TimeHelper
使用CakeTime
实用程序):
每当视图中使用Time->niceShort
时,我是否可以重写此类的公共属性以更改输出的日期格式?(这是“monkey patching”?)如果是,那么什么是好的/干净的方法
或者我应该编写一个扩展CakeTime
的新类,这是否意味着必须在视图中将$this->Time
更改为$this->mynewspiffingscustomisedtime
(我不希望这样做,因为其他习惯使用Cake的Time
的人正在处理项目)?我不知道仅仅为了改变一个属性,这是否会有点过分。旧:
不需要,您只需比较:
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',strotime($date));
调用CakePHP包装器。CakePHP包装器被定义为$this->Time->format('format',$date);
并调用前面列出的php函数
如果你计划在任何时候升级,你都不应该个性化基本代码。唯一的方法(我现在能想到)要继续调用$this->Time并扩展基本代码,需要实现一个名为
Time
的插件,并将其包含在$helper
和/或$component
成员变量Time.mySpiffyTimeThingo
中,其中mySpiffyTimeThingo是组件或助手的名称。这些插件可以扩展/覆盖当前的CakePHP CakeTime函数。为什么不扩展帮助程序
在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.
}
甚至可以将默认的Time
更改为callmyTime
,这样您就不需要更改已编写代码中的任何其他内容:
public $helpers = array('Time' => array('className' => 'myTime'));
不适合更改库代码。创建类并基本上扩展create new helper,并使用cakephp内置的helper扩展new helper。这似乎更多地是为了确定日期是今天/昨天,而不是更改输出日期的格式?您是说希望它显示得更像今天、时间和昨天吗y、 每一个例子的时间?例如,一周前,时间;去年,时间?不;见原始问题的第一段。我还改写了最后几段,以使其更清楚。谢谢。我编辑了我的答案,以更接近您所寻找的内容,我想。您的问题仍然(至少对我自己而言)没有完全清楚,所以我对完整的主题进行了深入的探讨。注意:在当前版本的CakePHP(2.6.x)中,TimeHelper::format()参数的正确顺序与上面显示的相反。应该是“$timestamp”,format\u string`。
public $helpers = array('myTime');
public $helpers = array('Time' => array('className' => 'myTime'));