Skip to content

Instantly share code, notes, and snippets.

@whizark
Last active August 29, 2015 14:04
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 whizark/ab92a769a04a6f9c5f28 to your computer and use it in GitHub Desktop.
Save whizark/ab92a769a04a6f9c5f28 to your computer and use it in GitHub Desktop.
Register WordPress $GLOBALS as services with a container (The simplest way) #test #wordpress
<?php
// This is just an example FOR WORDPRESS USERS.
//
// To make this better:
// * use namespace/class/closure etc.
// * use autoloader
// * create & use service provider classes
// * create & use factory for WP_Query, WP_User etc.
// interface ContainerInterface
// {
// public function add($key, $value);
// }
//
// // DI/IoC/AOP container
// class Container implements ContainerInterface
// {
// // implement
// }
$container = new Container();
add_action(
'mu_plugins_loaded',
function () use ($container) {
$container->add('wpdb', $GLOBALS['wpdb']);
// Note: WP_Locale can be instantiated early when an error occurs.
// Note: You may instantiate WP_Styles, WP_Scripts early.
// $wp_styles = isset($GLOBALS['wp_styles']) ? $GLOBALS['wp_styles'] : new WP_Styles();
// $container->add('wp_styles', $wp_styles);
//
// $wp_styles = isset($GLOBALS['wp_scripts']) ? $GLOBALS['wp_scripts'] : new WP_Scripts();
// $container->add('wp_scripts', $wp_scripts);
},
~PHP_INT_MAX
);
add_action(
'setup_theme',
function () use ($container) {
$container->add('wp_the_query', $GLOBALS['wp_the_query']);
$container->add('wp_query', $GLOBALS['wp_query']);
$container->add('wp_rewrite', $GLOBALS['wp_rewrite']);
$container->add('wp', $GLOBALS['wp']);
$container->add('wp_widget_factory', $GLOBALS['wp_widget_factory']);
$container->add('wp_roles', $GLOBALS['wp_roles']);
},
~PHP_INT_MAX
);
add_action(
'after_setup_theme',
function () use ($container) {
$container->add('wp_locale', $GLOBALS['wp_locale']);
},
~PHP_INT_MAX
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment