Skip to content

Instantly share code, notes, and snippets.

@rgadon107
Created January 29, 2021 21:43
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 rgadon107/a312af2dc31e8c5d77c2085509e7390b to your computer and use it in GitHub Desktop.
Save rgadon107/a312af2dc31e8c5d77c2085509e7390b to your computer and use it in GitHub Desktop.
Solution to Code Challenge 5 from "Refactoring Tweaks Workbook"
/* Code Challenge 5, from “Refactoring Tweaks Workbook” by Tonya Mork ( 2016, LeanPub (https://leanpub.com/littlegreenbookofrefactoringtweaks-workbook) ). */
/***************************************************
*
* Original code to be refactored.
*
**************************************************/
class Session {
/**
* Flag whether or not the internal collection has been changed.
*
* @var bool
*/
protected $dirty = false;
..
/**
* Write the data from the current session to the data storage system.
*/
public function write_data() {
$option_key = "_prefix_session_{$this->session_id}";
// Only write the collection to the DB if it's changed.
if ( $this->dirty ) {
if ( false === get_option( $option_key ) ) {
add_option( "_prefix_session_{$this->session_id}", $this->container, '', 'no' );
add_option( "_prefix_session_expires_{$this->session_id}", $this->expires, '', 'no' );
} else {
delete_option( "_prefix_session_{$this->session_id}" );
add_option( "_prefix_session_{$this->session_id}", $this->container, '', 'no' );
}
}
}
..
}
/***************************************************
*
* Refactored Code
*
**************************************************/
class Session {
/**
* Flag whether or not the internal collection has been changed.
*
* @var bool
*/
protected $dirty = false;
/**
* Write the data from the current session to the data storage system.
*/
public function write_data() {
if ( ! $this->is_dirty() ) {
return;
}
$this->write_collection_to_db();
}
protected function is_dirty( $dirty ) {
return $dirty = true;
}
protected function write_collection_to_db() {
$option_key = "_prefix_session_{$this->session_id}";
if ( false === get_option( $option_key ) ) {
add_option( "_prefix_session_{$this->session_id}", $this->container, '', 'no' );
add_option( "_prefix_session_expires_{$this->session_id}", $this->expires, '', 'no' );
} else {
delete_option( "_prefix_session_{$this->session_id}" );
add_option( "_prefix_session_{$this->session_id}", $this->container, '', 'no' );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment