-
-
Save Oxicode/34cb5796b97b7b7cd96435c4d6a3666e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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