当前日期在doctrine / php中的最佳做法 [英] Best practices with current date in doctrine/php

查看:61
本文介绍了当前日期在doctrine / php中的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不得不根据当前日期来获取带有学说的数据,我想知道关于它的最佳实践是什么。我是否应该:

i had to retrieve datas with doctrine based on current date, i wanted to know what was the best practices about it. Should i :


  • 将代表当前时间的DateTime对象作为函数的参数传递给我,以便我可以轻松地测试函数

  • 在我的QueryBuilder的setParameter()中实例化一个DateTime对象

  • 或者仅在我的查询构建器中使用mysql的CURRENT_TIMESTAMP()

这些选择让我有些迷惑,为什么我不选择一个选项。

I'm a bit lost with those choices and why should i or not choose an option.

推荐答案

如果您使用的是Doctrine,则按照定义,不应使用最后一个选项,因为Doctrine具有创建查询的功能。因此,可以将DateTime对象作为参数传递给例如存储库函数,和/或在使用QueryBuilder时使用实例化新的DateTime对象。

If you're using Doctrine, then the last option should by definition not be used, as Doctrine has functionality for the creation of queries. So either pass the DateTime object as a param, for example to a repository function and/or use instantiate a new DateTime object when you're using the QueryBuilder.

作为函数的参数,例如在存储库中:

As a param for a function, e.g. in Repository:

function getStuff(DateTime $from)
{ 
    $criteria = new Criteria();
    $criteria->andWhere(
        $criteria::expr()->eq('from', $from)
    );

    return $this->matching($criteria);
}

或者如果您始终想使用 now:

Or if you always want to use "now":

function getStuff()
{ 
    $criteria = new Criteria();
    $criteria->andWhere(
        $criteria::expr()->eq('from', new DateTime('now'))
    );

    return $this->matching($criteria);
}

为什么作为参数

您可能希望允许用户设置日期(和/或时间),并因此从控制器和/或服务中传递日期

You might want to allow the date (and/or time) to be set by the user and as such let it be passed from a Controller and/or Service

为什么要现在

您可能希望始终从/直到现在返回某些内容。

You might want to always return something from/until now.

注意,您可以使用其他'now' http://php.net/manual/en/datetime.formats.relative.php rel = nofollow noreferrer>相对格式以设置DateTime默认值,例如:

Mind, instead of 'now' you could use another relative format to set a DateTime default, for example:

$dateTime = new DateTime('last day of'); // Sets date to last day of the current month






更多使用教义标准

和完整的文档

这篇关于当前日期在doctrine / php中的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆