Skip to content

Instantly share code, notes, and snippets.

@viniciusbig
Forked from denchev/gist:8209318
Created October 24, 2018 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viniciusbig/f0ffc9db7ca05c0bdba42b5b711a6b03 to your computer and use it in GitHub Desktop.
Save viniciusbig/f0ffc9db7ca05c0bdba42b5b711a6b03 to your computer and use it in GitHub Desktop.
<?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