Created
April 2, 2016 21:12
-
-
Save avclark/9a72d4051d8d46fce076bfb96aa3be3f to your computer and use it in GitHub Desktop.
Class Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Init_Menu_Item { | |
public function __construct() { | |
$this->initialize(); | |
} | |
public function initialize() { | |
add_action( 'admin_menu', array( $this, 'init_menu_item') ); | |
} | |
public function init_menu_item() { | |
add_options_page( | |
__( 'Better WP Environments', 'bwpe' ), | |
__( 'Better WP Environments', 'bwpe' ), | |
'manage_options', | |
'bwpe-options', | |
'render_options_display' | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Without knowing the full context of this class (that is, is it part of another set of classes or is it just doing this one thing?), it's hard for me to say whether or not this is exactly how I'd do it.
But, for the most part, I think this looks okay. There are some changes I'd make, though:
initialize
function in the constructor; otherwise, you might as well just put the body ofinitialize
in the constructor. Instead, use the constructor to set properties. If there are none, then disregard it (PHP will always provide an implied, default, and empty constructor).add_action
could be used be another class or not. It depends on how this class intends to be used. If you want to really de-couple the business logic and the integration with WordPress, I'd create a second class that takes an instance ofInit_Menu_Item
and then wires theinit_menu_item
function in the hook. I'll have an example below.Init_Menu_Item
) isn't standard practice and it's really good OOP. Instead, name it for what it is (which as far as I can tell is a menu item for Better WP Environments). So, with that said, I'd probably so something like this:First, define the main menu item class:
Secondly, introduce a class for specifically handling the hook registration:
Then I'd have a plugin bootstrap file do something like this:
From here you may be able to call
bwpe_setup_menus()
right after it's defined or you may need to have it registered with a hook. It depends all on when you're wanting this to fire. It needs to be when theadmin_menu
hook is available, if nothing else.