How to include class from addon after to be sure one class exists in the main plugin?

I found this answer which seems to be good.
I used the hooks plugins_loaded and _admin_menu.
The hook _admin_menu is before admin_menu so I can add an admin page menu.

FooAddon.php

namespace PluginFoo;

class FooAddon{ 

    public function __construct(){

        // Install needed components on plugin activation
        register_activation_hook( __FILE__, array( $this, 'install' ) );

        // Include dependencies
        add_action('plugins_loaded',  array( $this , 'include_dependencies' ) );

        // Initialize the components
        add_action('_admin_menu',  array( $this , 'init' ) );

    }

    public function include_dependencies(){
        ... 
        if( class_exists( "PluginFoo\\Admin\\Heading" ) ){
            if( file_exists( PLUGIN_ADDON_DIR_PATH."dir/MyClass.php" ) ) {
                   include_once 'dir/MyClass.php';
              }
        }
        ...
     }

     public function init(){
        if( is_admin() ){
            if( ! class_exists( "PluginWPGroupSubs\\Admin\\MYCLASS" ) ) {
                error_log("MyClass was not included");
            }else{
                new MyClass();
            }
        }

    }

}
new FooAddon();

Leave a Comment