【问题标题】:Best practices with current date in doctrine/php学说/php中当前日期的最佳实践
【发布时间】:2019-01-23 22:03:47
【问题描述】:
我必须使用基于当前日期的原则来检索数据,我想知道关于它的最佳实践是什么。我应该:
- 传递一个代表当前时间的 DateTime 对象作为我的函数的参数,以便我可以轻松地测试我的函数
- 在我的 QueryBuilder 的 setParameter() 中实例化一个 DateTime 对象
- 或者只是在我的查询生成器中使用 mysql 的 CURRENT_TIMESTAMP()
我对这些选择有点迷茫,为什么我应该或不选择一个选项。
【问题讨论】:
标签:
php
datetime
doctrine-orm
query-builder
【解决方案1】:
如果您使用的是 Doctrine,那么根据定义不应使用最后一个选项,因为 Doctrine 具有创建查询的功能。因此,要么将 DateTime 对象作为参数传递,例如传递给存储库函数和/或在使用 QueryBuilder 时实例化一个新的 DateTime 对象。
作为函数的参数,例如在存储库中:
function getStuff(DateTime $from)
{
$criteria = new Criteria();
$criteria->andWhere(
$criteria::expr()->eq('from', $from)
);
return $this->matching($criteria);
}
或者如果你总是想使用“现在”:
function getStuff()
{
$criteria = new Criteria();
$criteria->andWhere(
$criteria::expr()->eq('from', new DateTime('now'))
);
return $this->matching($criteria);
}
为什么作为参数
您可能希望允许用户设置日期(和/或时间),因此让它从控制器和/或服务传递
为什么是“现在”
您可能希望始终从/到现在返回一些东西。
请注意,您可以使用另一个 relative format 来设置 DateTime 默认值,而不是 'now',例如:
$dateTime = new DateTime('last day of'); // Sets date to last day of the current month
More on using Doctrine Criteria
And the full class docs