📜 ⬆️ ⬇️

time () or now () as a dependency on the global environment

At once I will say that there will be no revelation by an experienced programmer, the rake is trivial.
Everyone knows that the $ _POST, $ _SESSION, $ _SERVER, etc. superglobal arrays are unacceptable in models, as this makes it impossible to complicate code testing and its reuse. But if superglobal arrays, after all, if you wish, you can “hack” (of course, this is already beyond good and evil), then another less obvious dependence on the global environment is already in any way.
I'm talking about time - you add such a dependency to your code when you use time () (date () without the timestamp argument) in the php model or now () (sysdate in Oracle) in the MySql query. Hacking the server time to find out how your request will behave tomorrow or yesterday is not a trivial task.
How does this happen.

You have a table with an Event billboard and the task is to display today's events, pens immediately reach out to write now ():
function findToday() { $sql = "SELECT * FROM event WHERE event_date >= date( now() ) AND event_date < date( now() + interval 1 day)"; } 

Do not do this :)
First, how to test, what will the query show in a week (in reality, logic is certainly more complicated than in the example)?
Secondly, if tomorrow, you need a calendar showing events for an arbitrary date, you will have to duplicate the code.
It is better to do so immediately:
UPDATE:
 function findToday() { $this->findByDate( new DateTime() ); } function findByDate( DateTime $dateTime ) { $dateStart = $dateTime->format('Ymd H:00:00'); $dateEnd = $dateTime->format('Ymd 23:59:59'); $sql = "SELECT * FROM event WHERE event_date >= '$dateStart' AND event_date <= '$dateEnd' "; } 

Now you can test and call the method for an arbitrary date.

UPD. 15 anonymous cons, people! 14 people have added the article to your favorites, explain to everyone what is wrong in the article? Or put a minus - it's like sex?

')

Source: https://habr.com/ru/post/201324/


All Articles