$em = $this->getDoctrine()->getEntityManager();
// get latest toplist
$last = $em->getRepository('RadioToplistBundle:Toplist')->findOneBy(
array('number' => 'DESC')
);
// get current year and week of the year
$week = date('W');
$year = date('Y');
// if:
// [case 1]: $last is null, meaning there are no toplists in the database
// [case 2]: $last->getYear() or $last->getWeek() do not match current
// year and week number, meaning that there are toplists in the
// database, but not for current week
// then:
// create new toplist entity (for current week of current year)
// else:
// do nothing (return)
if($last && $last->getYear() == $year && $last->getWeek() == $week)
return;
else {
$new = new Toplist();
$new->setYear($year);
$new->setWeek($week);
$em->persist($new);
$em->flush();
}
This code is executed with each request to view toplist results (frontend) or list of toplists (backend). Anytime someone wants to access the toplist we first check if we should create a new toplist entity (for new week).
Is it possible that:
And so.. after a few seconds we have 2 toplist entities for current week.
Is this possible?
How should I prevent this?
Yes, it is possible. You should use locks while performing calculations based on db values (which are than stored back in the db).
Read more on locks in doctrine's docs: Locking support