WP Register – PHP registry for WordPress development

One of the things I think could be improved in alot of PHP code is the use of global level variables. While it’s not ideal to use a global system for variables, sometimes it’s necessary for reporting error messages or storing data for use elsewhere in an application

While the $_SESSION can be used, I’m a fan of taking the OO approach and relying on the magic _get and _set methods in PHP 5.

Anway, below is the plugin code for setting up a simple PHP 5 registry

class WP_Registry {

/* Where everything is stored */
private static $_arrRegistry = array( );

public function __construct() {

}

/**
* Set Magic Method
*
* Sets data to the registry
*
* @param string $name
* @param mixed $value
*/
final public function __set( $name, $value ) {
self::set( $name, $value );
}

/**
* Get Magic Method
*
* Gets from the registry
*
* @param string $name
* @return mixed
*/
final public function __get( $name ) {
return self::get( $name );
}

/**
* Set
*
* Sets to the registry
*
* @param string $name
* @param mixed $value
*/
final public static function set( $name, $value ) {
self::$_arrRegistry[$name] = $value;
}

/**
* Get
*
* Gets from the registry
*
* @param string $name
* @return mixed
*/
final public static function get( $name ) {
if ( array_key_exists( $name, self::$_arrRegistry ) ) {
return self::$_arrRegistry[$name];
} else {
return false;
}
}

/**
* Delete
*
* Deletes item from the registry
*
* @param string $name
* @return void
*/
final public static function delete( $name ) {
unset( self::$_arrRegistry[$name] );
}

/**
* Get All
*
* Gets everything set to the registry. Mainly
* a debugging thing more than anything
*
* @return array
*/
final public static function getAll() {
return self::$_arrRegistry;
}

}



To implement the Registry simple:


WP_Registry::set( 'some_key', $some_value );

And to get the item from the registry:


WP_Registry::get( 'some_key' );

To delete something from the registry:


WP_Registry::delete( 'some_key' );

That’s really it. Super simple but super handy if you’re trying to log a bunch items/variables in memory.

Credit to Simon Emms for the initial code (http://www.simonemms.com/2011/02/08/codeigniter-registry/)

TTFN

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s