Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active May 26, 2017 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/4f5087613f01dcb35b7fb5e79c69401d to your computer and use it in GitHub Desktop.
Save tommcfarlin/4f5087613f01dcb35b7fb5e79c69401d to your computer and use it in GitHub Desktop.
[WordPress] Rapid Prototyping: Introducing Autoloading
<?php
/**
* Automatically loads the specified file.
*
* @package McFarlin\TFP
*/
namespace McFarlin\TFP;
/**
* Automatically loads the specified file.
*
* Examines the fully qualified class name, separates it into components, then creates
* a string that represents where the file is loaded on disk.
*
* @package McFarlin\TFP;
*/
spl_autoload_register(function( $filename ) {
// First, separate the components of the incoming file.
$file_path = explode( '\\', $filename );
// Get the last index of the array. This is the class we're loading.
if ( isset( $file_path[ count( $file_path ) - 1 ] ) ) {
$class_file = strtolower(
$file_path[ count( $file_path ) - 1 ]
);
/**
* The classname has an underscore, so we need to replace it
* with a hyphen for the file name.
*/
$class_file = str_ireplace( '_', '-', $class_file );
$class_file = "class-$class_file.php";
}
/**
* Find the fully qualified path to the class file by iterating through the $file_path array.
* We ignore the first index since it's always the top-level package. The last index is always
* the file so we append that at the end.
*/
$fully_qualified_path = trailingslashit(
dirname(
dirname( __FILE__ )
)
);
/**
* We start at the second index of the namespace because our directory
* structure does not include 'McFarlin/TRP'.
*/
for ( $i = 2; $i < count( $file_path ) - 1; $i++ ) {
$dir = strtolower( $file_path[ $i ] );
$fully_qualified_path .= trailingslashit( $dir );
}
$fully_qualified_path .= $class_file;
// Now we include the file.
if ( file_exists( $fully_qualified_path ) ) {
include_once( $fully_qualified_path );
}
});
<?php
/**
* Three Recent Posts
*
* @package TRP
* @author Tom McFarlin
* @copyright 2017 Tom McFarlin
* @license MIT
*
* @wordpress-plugin
* Plugin Name: Three Recent Posts
* Plugin URI: https://tommcfarlin.com/three-recent-posts/
* Description: Displays the three mot recent posts in your post editor screen.
* Version: 1.0.0
* Author: Tom McFarlin
* Author URI: https://tommcfarlin.com
* Text Domain: three-recent-posts
* License: GPL
* License URI: http://www.gnu.org/licenses/gpl-3.0.txt
*/
namespace McFarlin\TRP;
use McFarlin\TRP\Display\Meta_Box;
// Import the autoloader.
include_once 'Includes/autoload.php';
add_action( 'add_meta_boxes', __NAMESPACE__ . '\\trp_start' );
/**
* Starts the plugin.
*/
function trp_start() {
$meta_box = new Meta_Box( dirname( __FILE__ ) );
$meta_box->init();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment