Skip to content

Instantly share code, notes, and snippets.

@tfrommen
Last active September 7, 2016 05:26
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 tfrommen/51d80f6d327d4d254ad9ace09b8d3fdc to your computer and use it in GitHub Desktop.
Save tfrommen/51d80f6d327d4d254ad9ace09b8d3fdc to your computer and use it in GitHub Desktop.
Save and restore the current WordPress network state.
<?php
/**
* Save and restore the current network state.
*
* By using this class, you can avoid unnecessary
* switch_to_blog()-restore_current_blog()-switch_to_blog()-... excesses.
*/
class NetworkState {
/**
* @var int
*/
private $site_id;
/**
* @var int[]
*/
private $stack;
/**
* @var bool
*/
private $switched;
/**
* Constructor. Sets up the properties.
*/
public function __construct() {
global $_wp_switched_stack, $switched;
$this->site_id = get_current_blog_id();
$this->stack = $_wp_switched_stack;
$this->switched = $switched;
}
/**
* Returns a new instance representing the current network state.
*
* @return static Network state object.
*/
public static function create() {
return new static();
}
/**
* Restores the saved network state.
*
* @return void
*/
public function restore() {
switch_to_blog( $this->site_id );
$GLOBALS['_wp_switched_stack'] = $this->stack;
$GLOBALS['switched'] = $this->switched;
}
}
@dnaber-de
Copy link

How about moving the dependencies (site ID, switched stack, switched) to the constructor parameter and rename the named constructor to create_from_globals()? Sure thing, the restore method would have to be renamed to restore_from_globals() too.

@tfrommen
Copy link
Author

tfrommen commented Sep 7, 2016

I don't see a use case for storing some network state that is not the current one (by using arbitrary values for the three parameters/properties). But, of course, one could allow for this. In that case, I would not call it create_from_globals, though, because maybe sometime (soon?) there won't be any globals anymore for this - or at least there is another non-global way to get these values. I would call it something like create_from_current_state() or so. And the method itself would just return new static(); just like it does now. That would mean that the constructor gets three individual parameters that all are optional and fall back to the current thing.

I'm not sure, though, that anyone really will make use of that - which fairly complicates the class...

In any case, the restore method should not be named restore_from_globals- because restoring only has to do with the inner state of the object, and not with globals. Yes, that inner state might (and it actually does, in my implementation) dependend on globals. But that's nothing that you're interested in or have to respect when restoring what you stored previously.

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