Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PSR 4 autoloader
<?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
You can’t perform that action at this time.