Skip to content

Instantly share code, notes, and snippets.

@mikeschinkel
Created January 18, 2012 01:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeschinkel/1630212 to your computer and use it in GitHub Desktop.
Save mikeschinkel/1630212 to your computer and use it in GitHub Desktop.
Proposing an add_autohook_support() function for WordPress.
<?php
/**
* Simplifies addition of WordPress hooks to a class.
*
* @param string|object $target - Class name or instance of class
* @param array $methods - List of methods and their overrides. Array key is method name, value is false (don't use as hook), alternate hook name, alternate priority, or alternate hook name and priority: array($hook_name,$priority).
*
* Author: Mike Schinkel
* Author URI: http://about.me/mikeschinkel/
*/
function add_autohook_support( $target, $methods = array() ) {
/**
* @var ReflectionMethod $method
*/
$class_reflector = new ReflectionClass( $target );
foreach ( $class_reflector->getMethods( ReflectionMethod::IS_PUBLIC ) as $method ) {
$hook_name = $method->name;
$priority = 10;
if ( isset( $methods[$method->name] ) ) {
if ( false === ( $method_args = $methods[$method->name] ) )
continue;
if ( is_string( $method_args ) ) {
$hook_name = $method_args;
} else if ( is_numeric( $method_args ) ) {
$priority = $method_args;
} else if ( is_array( $method_args ) ) {
list( $hook_name, $priority ) = $method_args;
}
}
add_filter( $hook_name, array( $target, $method->name ), $priority, $method->getNumberOfParameters() );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment