[wp-hackers] Plugins: Best practice for conditional loading of actions and file includes

Mike Schinkel mikeschinkel at newclarity.net
Tue Feb 9 15:04:20 UTC 2010


On Feb 8, 2010, at 11:47 AM, Otto wrote:
> Let's just say that you're far less likely to accidentally add a hook
> to an undeclared function if you have the hook and the function right
> next to each other.


FWIW, I find that code pattern to optimize for original programmer rather than optimizing for maintenance programmer and code reader.  Since original development is done once and maintenance and reading can be done hundreds or thousands of times it seems to me to be a no-brainer to optimize for the latter.

Here is the cut-down version of a pattern I tend to use for my plugins:

<?php
/*
Plugin Name: My Plugin
*/
MyPlugin::init();

class MyPlugin {
	const MY_CONST = 'My Value';
	static $my_vars = array();

	static function init() {
		add_action('<hook1>', array(__CLASS__,'<hook1_func>'));
		add_action('<hook2>', array(__CLASS__,'<hook2_func>'));
	}

	static function <hook1_func>() {
		// Do hook 1 stuff here
	}

	static function <hook2_func>() {
		// Do hook 2 stuff here
	}
}

Note this pattern has the benefit of adding only one named symbol into the global namespace and thus minimizes the likelihood of conflict and reduces the number of really long global names which is how many people try to minimize likelihood of symbol name conflict.

Of course I'm sure it can be improved and I'd love to hear any improvements.

-Mike


More information about the wp-hackers mailing list