Skip to content

Instantly share code, notes, and snippets.

@thefuxia
Created January 16, 2017 09:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thefuxia/ee39d04966e911e66256970f7ce4c1b8 to your computer and use it in GitHub Desktop.
Save thefuxia/ee39d04966e911e66256970f7ce4c1b8 to your computer and use it in GitHub Desktop.
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