Skip to content

Instantly share code, notes, and snippets.

@denchev
Created January 1, 2014 16:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save denchev/8209318 to your computer and use it in GitHub Desktop.
Save denchev/8209318 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, '+');
}
@TeddyBear06
Copy link

Good approach, thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment