Hey WordPress, How About a WP_Plugin Class?

Okay January is my month of ideas :) Let’s talk about plugins for a moment, shall we? Actions and filters are no secret to WordPress developers, right? Say, how many times do you type something like this in your plugins or theme files:

class Some_Plugin {
    function __construct() {
        add_action( 'admin_init', array( $this, 'admin_init' ) );
    }

    function admin_init() {
        // Whatever
    }
}

If you don’t, then you can stop reading now :) I’m addressing the naming technique here, the fact that admin_init is both an action tag, and a method that you assign to that action tag. So if I’m naming all my methods after actions and filters tags in WordPress, isn’t there a way to cut down the burden of having to add_action and add_filter all the time?

I’ve been thinking of an approach that could solve this problem in both, an easy to understand way, and a compatible way. Perhaps we’re lacking a WP_Plugin class in WordPress that would take care of this (along with a bunch of other things) for us, so that we can focus on writing our plugin, and not spend time matching tags to methods.

Here’s a concept that first popped into my mind, experimental and buggy, but something to get our heads thinking about it. If your class extends the WP_Plugin class, and your method’s name starts with a double-underscore prefix (or any other convention we may choose), and matches an existing action or filter, why not run the action or filter automatically without having to add_action or add_filter?

class Some_Plugin extends WP_Plugin {
    function __admin_init() {
        // Will run during admin_init
    }

    function __the_content( $content ) {
        // Will filter the_content
        return $content;
    }
}

Again, it’s just a thought and a lot of decisions should be made before implementing something like this. I went ahead and drafted a plugin file which works well to some extent. You can change the method name convention on line 18.

So my questions to you, dear reader are: is will this make things easier for the WordPress developers? Will this mess things up? What do you think of the prefix convention? How would you propose to handle the priority dilemma? What else could go into a WP_Plugin class?

Update! It seems like Reflection is a better approach at what I’m trying to do, and separating actions from filters logic too. Thanks so much for the heads up Ryan McCue, Kaiser and Daniel Dvorkin. Here’s Ryan’s improvement over my first Gist.

Thanks for stopping by and subscribing!