Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/*
Increase or decrease value in CakePHP with little footprint.
Add this to your AppModel.
Usage:
(in Controller)
$this->Model->increase('field_name', 1);
(in Model)
$this->decrease('field_name', 10);
*/
/**
* Updates a specific field with a given value
*
* @param $field Field name to update
* @param $value The step to use to increase the $field
* @return mixed
*/
private function _change($field, $value, $sign) {
$schema = $this->schema();
if( ! isset( $schema[$field] ) ) {
throw new Exception("No such field: " . $field, 1);
}
if( ! in_array( $sign, array('+', '-') ) ) {
throw new Exception("Not a valid mathematic sign", 1);
}
$sql = "UPDATE `" . $this->table . "` SET `" . $field . "` = `" . $field . "` " . $sign . " ? WHERE `" . $this->primaryKey . "` = ? LIMIT 1";
$result = $this->query($sql, array( $value, $this->id));
return $result;
}
/**
* Increase a specific $field with a given $value
*
* @param $field Field name to update
* @param $value The step to use to increase the $field
* @return mixed
*/
public function decrease($field, $value) {
return $this->_change($field, $value, '-');
}
/**
* Decrease a specific $field with a given $value
*
* @param $field Field name to update
* @param $value The step to use to increase the $field
* @return mixed
*/
public function increase($field, $value) {
return $this->_change($field, $value, '+');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment