将时间戳字段水合为 PEAR Date 对象
在我的 Symfony/Doctrine 应用程序中,我希望将数据库中的任何时间戳字段检索为 PEAR Date
对象而不是日期字符串。例如,如果我的模式是,
SomeEvent:
columns:
id:
type: integer
primary: true
start: timestamp
end: timestamp
我希望能够运行 Doctrine 查询来检索 SomeEvent
对象,并使 $anEvent->getStart()
成为 PEAR 日期对象。现在 Doctrine 为我提供了所有时间戳字段的字符串,这基本上是无用的。 (我还希望保存日期才能正常工作。)
实现此目的的最佳方法是什么?
我使用 Hydration 侦听器进行了研究,但看起来我必须为每个表注册该侦听器并对我想要转换的列名称进行硬编码。使用自定义水化器看起来并没有好多少,从那时起我就失去了使用任何其他核心水化方法的能力,而无需让我的日期再次成为字符串。
编辑:看起来 Doctrine 2 有一个功能正是我正在寻找的:自定义映射类型。不幸的是,该站点正在部署到不支持 PHP 5.3+ 的主机,因此 Doctrine 2 已退出。 :(
In my Symfony/Doctrine application, I would like any timestamp fields in my database to retreived as PEAR Date
objects instead of date strings. e.g. If my schema is
SomeEvent:
columns:
id:
type: integer
primary: true
start: timestamp
end: timestamp
I would like to be able to run a Doctrine query to retrieve SomeEvent
objects and have $anEvent->getStart()
be a PEAR Date
object. Right now Doctrine gives me strings for all timestamp fields which is basically useless. (I'd also like saving of Dates to work correctly.)
What's the best way to accomplish this?
I researched using a Hydration listener but it looks like I'd have to register that per table and hardcode the column names that I want to be converted. Using a custom Hydrator didn't look much better since then I lose the ability to use any of the other core hydration methods without having my dates be strings again.
EDIT: It looks like Doctrine 2 has a feature that's exactly what I'm looking for: Custom Mapping Types. Unfortunately this site is being deployed to a host that doesn't support PHP 5.3+ so Doctrine 2 is out. :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想出了一个很奇怪的方法,虽然我不太满意,但它确实有效。我创建了以下 2 个类:
并将 DateClassBehavior 添加到模型中每个表的定义中:
这负责在加载内容时创建
Date
对象。我还修改了实际的 PEARDate
类(我知道...不好)并添加了一个__toString()
方法,该方法返回$this->getDate()
。然后,当教义保存日期时,PHP 会自动将日期转换为正确的字符串。如果有人找到更好的方法来做到这一点,请发布。
I figured out a hacky way to do it that I'm not super happy with, but it works. I created the following 2 classes:
And added DateClassBehavior to the definition for each table in my model:
This takes care of creating the
Date
objects when things are loaded. I also modified the actual PEARDate
class (I know... bad) and added a__toString()
method that returns$this->getDate()
. PHP then automatically converts the dates to the correct string when doctrine saves them.If anyone finds a better way to do this please post it.