Skip to content

Instantly share code, notes, and snippets.

@Oxicode
Forked from denchev/gist:8209318
Created May 18, 2016 17:08
Show Gist options
  • Save Oxicode/34cb5796b97b7b7cd96435c4d6a3666e to your computer and use it in GitHub Desktop.
Save Oxicode/34cb5796b97b7b7cd96435c4d6a3666e 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