问题
i had to retrieve datas with doctrine based on current date, i wanted to know what was the best practices about it. Should i :
- Pass an DateTime object representing current time as parameter of my function so i could test easily my function
- Instantiate an DateTime object in the setParameter() of my QueryBuilder
- Or just use CURRENT_TIMESTAMP() of mysql in my query builder
I'm a bit lost with those choices and why should i or not choose an option.
回答1:
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);
}
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);
}
Why as a param
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
Why 'now'
You might want to always return something from/until now.
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
More on using Doctrine Criteria
And the full class docs
来源:https://stackoverflow.com/questions/54325192/best-practices-with-current-date-in-doctrine-php