OOP PHP — How to selectively call a specific method defined in a class' constructor?

Viewed 235

I'm learning to code Wordpress Multisite the OOP way, and since I'm pretty new to OOP now I am in a situation that I can't seem to solve on my own.

Specifically, I'm creating some classes to create admin pages (both at the network and subsite level) with an OOP approach. Here's my simplified code:

class AdminPage {

    public function __construct( $args ) {
        add_action( 'admin_menu', array( $this, 'add_admin_page' ) );
    }

    public function add_admin_page() {
        add_menu_page( // arguments );
    }

}

class AdminNetworkPage extends AdminPage {

    public function __construct( $args ) {
        add_action( 'network_admin_menu', array( $this, 'add_admin_page' ) );
     }

}

The code works, but as you can see I have to extend the AdminPage class with the sole purpose of changing the hook in the constructor ( I need admin_network_menu for admin pages at network level instead of admin_menu).

Is there a better way to do this? A way to have one class, put both hooks in the constructor of that class and then selectively call either one or the other?

Unfortunately, creating a new instance of the class ($page = new AdminPage) and then calling a method on it (e.g. $page->add_admin_page() ) won't work in this case, because then I get an error saying add_menu_page is undefined... It all has to happen in the constructor.

1 Answers

You could do something like this:

class AdminPage {

    public function __construct( $args, $networkPage = false ) {

        if($networkPage) {

            add_action( 'network_admin_menu', array( $this, 'add_admin_page' ) );

        } else {

            add_action( 'admin_menu', array( $this, 'add_admin_page' ) );

        }

    }

    public function add_admin_page() {

        add_menu_page( // arguments );

    }
}

And then pass a second parameter to the class to change which action you add, e.g.

$page = new AdminPage($args);
$networkPage = new AdminPage($args, true);

Whether or not this is better than just extending the class is debatable; I personally think there's nothing wrong with your initial setup, the point of OOP isn't to create as few classes as possible - if your code make more sense as two separate classes (with one extending the other) then there's nothing wrong with that.

Related