In order to manage concurrency - that is ensuring that data being saved to the database is not stale or already edited by some other user - in my CakePHP application I am using the modified
attribute in my edit functions. Below is a snippet of the code that is in my controller.
$this->MyModel->recursive = -1;
$event = $this->MyModel->findById($id);
$requestTimeStamp = new DateTime($this->request->data['MyModel']['modified']);
$dbTimeStamp = new DateTime($event['MyModel']['modified']);
if ($requestTimeStamp < $dbTimeStamp) {
$response = array(
'success' => false,
'id' => $id,
'message' => 'A concurrency error occurred while trying to save. Please try again');
echo json_encode($response);
exit;
} else {
//... continue processing
}
This code works fine - but as I try to optimize it across my application I am trying to figure out where best to place it. Is it best placed in my AppModel
class or is it better to create a Behavior
for the same or is it just best left in the controller? I suppose that an ideal option would consider performance and minimize the amount of class loading overhead as well as database access overhead.
Has anyone come across / solved this problem before? Thoughts / suggestions appreciated.
So I solved this by making concurrency check a part of my
AppModel->beforeSave()
method. Below is the code for reference of others