Created
December 16, 2012 08:00
-
-
Save victorjonsson/4304148 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
/** | |
* Class that contains all the options for my plugin. This class can be used as an | |
* ordinary PHP object (stdClass) | |
* | |
* @requires PHP version >= 5.1, WordPress version >= 1.6 | |
* @package MyPlugin | |
* @since 0.1 | |
*/ | |
class MyPlugin_Options implements IteratorAggregate { | |
public static function get($name, $default=false, $ns = null) | |
{ | |
$obj = new self($ns); | |
$val = $obj->$name; | |
if($val === false && $default !== false) | |
$val = $default; | |
return $val; | |
} | |
public static function set($name, $val, $ns=null) | |
{ | |
$obj = new self($ns); | |
$obj->$name = $val; | |
} | |
private $opt_name; | |
private $options; | |
public function __construct($ns = null) | |
{ | |
if($ns === null) | |
$ns = plugin_basename(__FILE__); | |
$this->opt_name = 'plugin_auto_options_'.$ns; | |
$this->options = get_option($this->opt_name, array()); | |
} | |
public function __get($name) | |
{ | |
return $this->exists($name) ? $this->options[$name] : false; | |
} | |
public function __set($name, $val) | |
{ | |
if($val === null) { | |
$this->delete($name); | |
} else { | |
$this->options[$name] = $val; | |
update_option($this->opt_name, $this->options); | |
} | |
} | |
public function __isset($name) | |
{ | |
return $this->exists($name); | |
} | |
public function __unset($name) | |
{ | |
$this->delete($name); | |
} | |
public function exists($name) { | |
return isset($this->options[$name]); | |
} | |
public function deleteAll() { | |
delete_option($this->opt_name); | |
} | |
public function delete($name) { | |
if( $this->exists($name) ) { | |
unset($this->options[$name]); | |
update_option($this->opt_name, $this->options); | |
} | |
} | |
public function getIterator() | |
{ | |
return new ArrayIterator($this->options); | |
} | |
} | |
// Use this class as an ordinary php object (stdClass) | |
$options = new MyPlugin_Options(); | |
$options->some_option = 'My value'; // the value can be of any type | |
if( isset($options->other_option) ) { | |
unset( $options->other_option ); | |
} | |
if( $options->perhaps_an_option ) { // trying to access undefined options will return false (no error triggered) | |
//... | |
} | |
foreach( $options as $opt_name => $val) { // tou can traverse the option object as if it were an array | |
// ... | |
} | |
// Static short hand functions | |
MyPlugin_Options::get('some_option', 'default value'); | |
MyPlugin_Options::set('some_option', null); // setting the option to null will remove it |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment