doctrine/php 当前日期的最佳做法
Best practices with current date in doctrine/php
我必须根据 当前日期 检索带有学说的数据,我想知道关于它的最佳实践是什么。我应该:
- 传递一个代表当前时间的 DateTime 对象作为我的函数的参数,这样我就可以轻松地测试我的函数
- 在我的 QueryBuilder 的 setParameter() 中实例化一个 DateTime 对象
- 或者在我的查询构建器中使用 mysql 的 CURRENT_TIMESTAMP()
我对这些选择有点迷茫,为什么我应该或不选择一个选项。
如果您正在使用 Doctrine,那么根据定义不应使用最后一个选项,因为 Doctrine 具有创建查询的功能。因此,要么将 DateTime 对象作为参数传递,例如传递给存储库函数 and/or 使用 QueryBuilder 时实例化一个新的 DateTime 对象。
作为函数的参数,例如在存储库中:
function getStuff(DateTime $from)
{
$criteria = new Criteria();
$criteria->andWhere(
$criteria::expr()->eq('from', $from)
);
return $this->matching($criteria);
}
或者如果你总是想使用 "now":
function getStuff()
{
$criteria = new Criteria();
$criteria->andWhere(
$criteria::expr()->eq('from', new DateTime('now'))
);
return $this->matching($criteria);
}
为什么作为参数
您可能希望允许用户设置日期(and/or 时间),因此让它从控制器 and/or 服务
传递
为什么'now'
您可能希望现在总是 return 一些东西 from/until。
请注意,您可以使用另一个 relative format 来设置日期时间默认值,而不是 'now'
,例如:
$dateTime = new DateTime('last day of'); // Sets date to last day of the current month
我必须根据 当前日期 检索带有学说的数据,我想知道关于它的最佳实践是什么。我应该:
- 传递一个代表当前时间的 DateTime 对象作为我的函数的参数,这样我就可以轻松地测试我的函数
- 在我的 QueryBuilder 的 setParameter() 中实例化一个 DateTime 对象
- 或者在我的查询构建器中使用 mysql 的 CURRENT_TIMESTAMP()
我对这些选择有点迷茫,为什么我应该或不选择一个选项。
如果您正在使用 Doctrine,那么根据定义不应使用最后一个选项,因为 Doctrine 具有创建查询的功能。因此,要么将 DateTime 对象作为参数传递,例如传递给存储库函数 and/or 使用 QueryBuilder 时实例化一个新的 DateTime 对象。
作为函数的参数,例如在存储库中:
function getStuff(DateTime $from)
{
$criteria = new Criteria();
$criteria->andWhere(
$criteria::expr()->eq('from', $from)
);
return $this->matching($criteria);
}
或者如果你总是想使用 "now":
function getStuff()
{
$criteria = new Criteria();
$criteria->andWhere(
$criteria::expr()->eq('from', new DateTime('now'))
);
return $this->matching($criteria);
}
为什么作为参数
您可能希望允许用户设置日期(and/or 时间),因此让它从控制器 and/or 服务
传递为什么'now'
您可能希望现在总是 return 一些东西 from/until。
请注意,您可以使用另一个 relative format 来设置日期时间默认值,而不是 'now'
,例如:
$dateTime = new DateTime('last day of'); // Sets date to last day of the current month