Can I hook inside another hook?

When it comes to the oop way of doing things you need more than just the class, you also need to instantiate it as an object at some point if you want the action to fire.

class myClass{

    function __construct(){
        add_action( 'init', array( $this, 'someFun' ) );
    }

    function someFun(){
        include( 'my-script.php' );
    }

}
//instantiate an instance of myClass
new myClass();

followed by, in my-script.php,

class anotherClass{

    function __construct(){
        add_action( 'wp', array( $this, 'moreFun' ) );
    }

    function moreFun(){
        //do something.
    }

}

won’t do anything more than include the definition of anotherClass. It’s moreFun function won’t be called; nothing else will happen.

To get it to do moreFun at wp you must also instantiate anotherClass, e.g.

    function someFun(){
        include( 'my-script.php' );
        new anotherClass();
    }

However, what’s the point in this? Why include my-script.php in someFun when you could have included it initially and not risked missing it somehow elsewhere?

The only reason I can think for doing this is if you want to have more than one definition of anotherClass (something that is quite poor practice in general).

It is better to do this:

class pluginRootClass{

    function __construct(){
        //include all your class definitions
        include( 'my-script.php' );
        include( 'scripty.php' )

        //then do your actions
        add_action( 'init', array( $this, 'someFun' ) );
    }

    function someFun(){
        new anotherClass();
    }

}

//instantiate an instance of pluginRootClass
new pluginRootClass();

This works a lot better because there’s no chance of accidentally doing a $x = new anotherClass(); when anotherClass isn’t defined because the action ‘init’ (or whichever action it is) hasn’t fired yet and so breaking everything.

In addition, for the pluginRootClass there is the risk of it being instantiated more than once. Thus calling the __construct function more than once, thus including the same class definitions more than once, thus causing an error. Hence it is better to stop this from happening by making a singleton of pluginRootClass.

function myPlugin(){
    //If object already exists return it, if not create it, save it and return it
    if( ! ( $ob = wp_cache_get( 'root', 'plugin-namespace' ) ) ){
        $ob = new pluginRootClass();
        wp_cache_set( 'root', $ob, 'plugin-namespace' );
    }
    return $ob;
}
myPlugin();

and then only calling the class by using the function myPlugin.

Leave a Comment