| 1 |
<?php |
| 2 |
namespace ABlocks; |
| 3 |
|
| 4 |
if ( ! defined( 'ABSPATH' ) ) { |
| 5 |
exit; // Exit if accessed directly. |
| 6 |
} |
| 7 |
|
| 8 |
class Autoload { |
| 9 |
|
| 10 |
/** |
| 11 |
* Instance |
| 12 |
* |
| 13 |
* @access private |
| 14 |
* @var object Class Instance. |
| 15 |
* @since 1.1.0 |
| 16 |
*/ |
| 17 |
private static $instance; |
| 18 |
|
| 19 |
/** |
| 20 |
* Autoload directories for different namespaces. |
| 21 |
* |
| 22 |
* @var array |
| 23 |
*/ |
| 24 |
private $autoload_directories = array( |
| 25 |
'ABlocks' => ABLOCKS_ROOT_DIR_PATH . 'includes/', |
| 26 |
); |
| 27 |
|
| 28 |
/** |
| 29 |
* Initiator |
| 30 |
* |
| 31 |
* @since 1.1.0 |
| 32 |
* @return object initialized object of class. |
| 33 |
*/ |
| 34 |
public static function get_instance() { |
| 35 |
if ( ! isset( self::$instance ) ) { |
| 36 |
self::$instance = new self(); |
| 37 |
} |
| 38 |
return self::$instance; |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* Register autoload directories for namespaces. |
| 43 |
* |
| 44 |
* @param string $namespace Namespace to autoload. |
| 45 |
* @param string $directory Directory path for the namespace. |
| 46 |
*/ |
| 47 |
public function add_namespace_directory( $namespace, $directory ) { |
| 48 |
$this->autoload_directories[ $namespace ] = $directory; |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Autoload classes. |
| 53 |
* |
| 54 |
* @param string $class Class name. |
| 55 |
*/ |
| 56 |
public function autoload( $class ) { |
| 57 |
foreach ( $this->autoload_directories as $namespace => $directory ) { |
| 58 |
if ( 0 === strpos( $class, $namespace ) ) { |
| 59 |
$class_to_load = $class; |
| 60 |
$filename = strtolower( |
| 61 |
preg_replace( |
| 62 |
[ '/^' . $namespace . '\\\/', '/([a-z])([A-Z])/', '/_/', '/\\\/' ], |
| 63 |
[ '', '$1-$2', '-', DIRECTORY_SEPARATOR ], |
| 64 |
$class_to_load |
| 65 |
) |
| 66 |
); |
| 67 |
$file = $directory . $filename . '.php'; |
| 68 |
// If the file is readable, include it. |
| 69 |
if ( is_readable( $file ) ) { |
| 70 |
require_once $file; |
| 71 |
} |
| 72 |
} |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
/** |
| 77 |
* Constructor |
| 78 |
* |
| 79 |
* @since 1.1.0 |
| 80 |
*/ |
| 81 |
public function __construct() { |
| 82 |
spl_autoload_register( [ $this, 'autoload' ] ); |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
|
| 87 |
Autoload::get_instance(); |
| 88 |
|