Skip to content

Commit

Permalink
Use standard module loader
Browse files Browse the repository at this point in the history
  • Loading branch information
eliot-akira committed Oct 5, 2024
1 parent 9fad77e commit 85eed7e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 21 deletions.
23 changes: 2 additions & 21 deletions index.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,29 +9,12 @@ function tangible_fields( $arg = false ) {
}
endif;

new class extends stdClass {
(include __DIR__ . '/module-loader.php')(new class extends StdClass {

public $name = 'tangible_fields';

// Remember to update the version - Expected format: YYYYMMDD
public $version = '20240614';

function __construct() {

$name = $this->name;
$priority = 99999999 - absint( $this->version );

remove_all_filters( $name, $priority );
add_action( $name, [ $this, 'load' ], $priority );

$ensure_action = function() use ( $name ) {
if ( ! did_action( $name ) ) do_action( $name );
};

add_action('plugins_loaded', $ensure_action, 0);
add_action('after_setup_theme', $ensure_action, 0);
}

// Dynamic methods
function __call( $method = '', $args = [] ) {
if ( isset( $this->$method ) ) {
Expand All @@ -43,8 +26,6 @@ function __call( $method = '', $args = [] ) {

function load() {

remove_all_filters( $this->name ); // First one to load wins

if (!class_exists('tangible\\framework')) {
$module_path = defined('TANGIBLE_FIELDS_IS_PLUGIN')
? __DIR__ . '/vendor/tangible/'
Expand All @@ -65,4 +46,4 @@ function load() {
do_action('tangible_fields_loaded', $fields);
}

};
});
32 changes: 32 additions & 0 deletions module-loader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php
/**
* Module loader: Ensure newest version is loaded when multiple plugins bundle
* the same module. Module must define: name, version (YYYYMMDD), and load().
* The function `load()` is called on `plugins_loaded` action at priority 0.
*/
return function($module) {

$name = $module->name;
$priority = 99999999 - absint( $module->version );

remove_all_filters( $name, $priority ); // Same version

add_action( $name, function() use ($module) {
remove_all_filters( $module->name ); // This instance wins
$module->load();
}, $priority );

$ensure_action = function() use ( $name ) {
if ( ! did_action( $name ) ) do_action( $name );
};

if (doing_action('plugins_loaded') || did_action('plugins_loaded')) {
$ensure_action();
return;
}

add_action('plugins_loaded', $ensure_action, 0);
add_action('after_setup_theme', $ensure_action, 0);

if (method_exists($module, 'init')) $module->init();
};

0 comments on commit 85eed7e

Please sign in to comment.