OOP noob在这里。我想利用CakePHP 2.3的短日期方法,以便在输出不是“今天”或“昨天”时更改日期格式时适当地“今天”或“昨天”。
示例视图:echo $this->Time->niceShort($user['User']['last_invited_on'];
。
我在lib/Cake/Utility/CakeTime.php
中找到了以下内容(Cake的TimeHelper
使用了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->MyNewSpiffingCustomisedTime
(我宁愿不像其他人那样做习惯使用Cake的Time
正在进行项目)?我想知道改变房产是否会有点过分。
答案 0 :(得分: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包装器。 CakePHP包装器定义为$this->Time->format('format', $date);
并调用我列出的上一个php函数。
如果您计划在任何时候升级,则不应个性化基本代码。唯一的方法(我现在可以想到)仍然可以调用$ this-&gt;时间和扩展基本代码将实现一个名为Time
的插件并包含在$helper
和/或$component
成员变量Time.mySpiffyTimeThingo
其中mySpiffyTimeThingo是组件或帮助程序的名称。这些可以扩展/覆盖当前的CakePHP CakeTime函数。
答案 1 :(得分: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'));