Skip to content

Instantly share code, notes, and snippets.

@andergmartins
Last active February 17, 2020 16:17
Show Gist options
  • Save andergmartins/73681d570eb0d78653edebee3846d098 to your computer and use it in GitHub Desktop.
Save andergmartins/73681d570eb0d78653edebee3846d098 to your computer and use it in GitHub Desktop.
Smart Loading for libraries in WordPress
<?php
/**
* Increment this number for every build.
* You can use an environment variable if you prefer.
*
* @var int
*/
$buildNumber = 1;
/**
* As higher as the build number is, smaller will be the loading priority - loading it first and creating the load flag.
* If the load flag is found, no other instance of the library should be loaded.
* This way we try to guarantee that only the most updated installed version is loaded.
*
* @var int
*/
$loadingPriority = PHP_INT_MAX - (int)$buildNumber;
/*
* Any unique action name is valid here. Just make sure to have a unique hook name for it.
* You will use it later to call the library loading, making sure to do it only
* from an event like 'init' or other that guarantee all the plugins are loaded
* and able to register its hooks.
*/
add_action('flipper_framework_load', function () {
if (!defined('FLIPPER_FRAMEWORK_LOADED')) {
// Load the library
define('FLIPPER_FRAMEWORK_VERSION', '0.1.0');
if (!class_exists('FlipperFramework\\Autoloader')) {
require_once 'src' . DIRECTORY_SEPARATOR . 'Autoloader.php';
}
Autoloader::register('FlipperFramework', __DIR__ . DIRECTORY_SEPARATOR . 'src');
// Set the loaded flag
define('FLIPPER_FRAMEWORK_LOADED', 1);
}
}, $loadingPriority);
@andergmartins
Copy link
Author

Instead of a build number, maybe we check for the version number. But on this case, instead of using the lower priority in the action we can register all the versions and check the highest one using version_compare before we really load the library.

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