Skip to content

Instantly share code, notes, and snippets.

@mikeschinkel mikeschinkel/1-example.php
Last active Aug 29, 2015

Embed
What would you like to do?
Examples of implementing helper methods for WPLib as instance methods (vs. static methods)
<?php
if ( WPLib::is_development() ) {
define( 'WP_DEBUG', true );
} else {
define( 'WP_DEBUG', false );
}
<?php
class _WPLib_Workflow {
var $runmode = 'dev';
static function on_load() {
WPLib::register_helper( __CLASS__ );
}
/**
* @return bool
*
* @static <------ THIS IS WHAT I NEED PHPSTORM TO RECOGNIZE
*/
function is_development() {
return 'dev' === $this->runmode;
}
}
_WPLib_Workflow::on_load();
<?php
class WPLib {
/**
* Register a "helper" method for this the WPLib class, or another class.
*
* @param string $helper_class
* @param string $class_to_help
*/
public static function register_helper( $helper_class, $class_to_help = 'WPLib' ) {
WP_Helper::_register_helper( $helper_class, $class_to_help );
}
/**
* Magic method that checks for "helper" methods when static calls are made.
*
* @param string $helper_method
* @param array $args
*
* @return mixed
*/
public static function __callStatic( $helper_method, $args ) {
return WP_Helper::_call_helper( get_called_class(), $helper_method, $args );
}
}
<?php
/**
* Class WPLib_Helper - Provides "Helper" functionality for WPLib and maybe other classes.
*/
class WPLib_Helper {
/**
* List of helper classes for the WPLib class
*
* @var array
*/
private static $_helpers;
/**
* Registers helper methods for WPLib or another class.
*
* @param string $helper_class
* @param string $class_to_help
*/
static function _register_helper( $helper_class, $class_to_help ) {
$methods = array_fill_keys( array_filter( get_class_methods( $helper_class ),
function( $element ) {
return '__' !== substr( $element, 0, 2 );
} ),
new $helper_class()
);
unset( $methods[ 'on_load' ] );
if ( ! isset( self::$_helpers[ $class_to_help ] ) ) {
self::$_helpers[ $class_to_help ] = $methods;
} else {
self::$_helpers[ $class_to_help ] += $methods;
}
}
/**
* Calls registered helper methods for the class being helped.
*
* @param string $class_helped
* @param string $helper_method
* @param array $args
* @return mixed
*/
static function _call_helper( $class_helped, $helper_method, $args ) {
if ( isset( self::$_helpers[ $class_helped ][ $helper_method ] ) ) {
return call_user_func_array( array( self::$_helpers[ $class_helped ][ $helper_method ], $helper_method ), $args );
} else {
$message = 'There is no helper method %s registered for class %s.';
trigger_error( sprintf( $message, $helper_method, $class_helped ), E_USER_ERROR );
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.