Created
January 16, 2017 09:53
-
-
Save thefuxia/ee39d04966e911e66256970f7ce4c1b8 to your computer and use it in GitHub Desktop.
PSR 4 autoloader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace T5\Files; | |
/** | |
* Simple PSR-4 autoloader | |
* See http://codereview.stackexchange.com/a/150308/318 for an explanation | |
*/ | |
class Autoload | |
{ | |
/** | |
* @var string | |
*/ | |
private $namespace; | |
/** | |
* @var string | |
*/ | |
private $dir; | |
/** | |
* @var int | |
*/ | |
private $length; | |
/** | |
* Autoload constructor. | |
* | |
* @param string $namespace Pass the namespace unescaped. | |
* @param string $dir | |
*/ | |
public function __construct( $namespace, $dir ) | |
{ | |
// Make sure it ends with a '\'. | |
$namespace = rtrim( $namespace, '\\' ) . '\\'; | |
$this->namespace = $namespace; | |
$this->length = strlen( $namespace ); | |
$this->dir = rtrim( $dir, '/' ) . '/'; | |
} | |
/** | |
* @param string $search | |
* @return void | |
*/ | |
public function load( $search ) | |
{ | |
if ( strncmp( $this->namespace, $search, $this->length ) !== 0 ) { | |
return; | |
} | |
$name = substr( $search, $this->length ); | |
$path = $this->dir . str_replace( '\\', '/', $name ) . '.php'; | |
if ( is_readable( $path ) ) { | |
require $path; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment