Last active
September 7, 2016 05:26
-
-
Save tfrommen/51d80f6d327d4d254ad9ace09b8d3fdc to your computer and use it in GitHub Desktop.
Save and restore the current WordPress network state.
This file contains 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 | |
/** | |
* 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 likecreate_from_current_state()
or so. And the method itself would just returnnew 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.