Skip to content

Instantly share code, notes, and snippets.

@tfrommen tfrommen/NetworkState.php
Last active Sep 7, 2016

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

dnaber-de commented Sep 7, 2016

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

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.