[wp-trac] [WordPress Trac] #37699: Death to Globals Episode #1: A Registry, A Pattern

WordPress Trac noreply at wordpress.org
Thu Aug 18 16:55:21 UTC 2016


#37699: Death to Globals Episode #1: A Registry, A Pattern
----------------------------+------------------
 Reporter:  wonderboymusic  |       Owner:
     Type:  enhancement     |      Status:  new
 Priority:  normal          |   Milestone:  4.7
Component:  General         |     Version:
 Severity:  normal          |  Resolution:
 Keywords:                  |     Focuses:
----------------------------+------------------

Comment (by wonderboymusic):

 if the class is loaded (and WordPress loads everything), why wouldn't `new
 wpdb` work?

 The key things here are:
 * **Existing** globals have to still exist for back compat, but the
 instantiation can be hidden
 * remove as many global imports as is possible from functions
 * lazy-load some class instances that aren't expected to always be in
 global scope (`$wp_hasher`, por ejemplo)
 * for some keys, perhaps enforce that the proper value is always returned,
 so that a plugin can't null out its value

 one of the things I noticed yesterday when fiddling with the POC - there
 are a ton of places in core that do:

 {{{
 function get_internet() {
     global $wpdb, $blog_id;
     ...
     $prefix = $wpdb->get_blog_prefix( $blog_id );
 }
 }}}

 In instances like this, getting rid of the globals isn't enough, seems
 like there should be a function that does this for you:

 {{{
 function get_site_prefix( $id = null ) {
     if ( ! $id ) {
         $id = get_current_blog_id();
     }

     $db = WP::get( 'wpdb' );
     return $db->get_blog_prefix( $id );
 }
 }}}

 The result is that many of the functions in core are just there as a
 procedural convenience. Often, we abstract out complex logic from
 functions to classes and then have functions do as little as possible
 while wrapping Singletons, or as a convenient way to act on instances in a
 simple way programmatically.

 Anything that results in fewer instances of importing global variables is
 an upgrade. Anything that abstracts it out so that if global scope
 disappears, the code will still work, is a vast improvement.

 This could happen in baby steps. `$wpdb` is so mission-critical to the
 codebase, I used it as an example to see if what I proposed is possible.

--
Ticket URL: <https://core.trac.wordpress.org/ticket/37699#comment:10>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list