Skip to content

Commit

Permalink
Fixed manual autoloader.
Browse files Browse the repository at this point in the history
  • Loading branch information
typerandom committed Jul 9, 2014
1 parent e942706 commit 6a7a5cc
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 38 deletions.
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ UserApp relies on the autoloading features of PHP to load its files when needed.

#### Not using Composer? Use the library's own autoloader

require 'lib/Autoloader.php';
UserApp\Autoloader::register();
require 'autoload.php';

### Creating your first client

Expand Down
5 changes: 5 additions & 0 deletions autoload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

require __DIR__.'/lib/UserApp/Autoloader.php';

UserApp\Autoloader::register();
36 changes: 0 additions & 36 deletions lib/Autoloader.php

This file was deleted.

47 changes: 47 additions & 0 deletions lib/UserApp/Autoloader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace UserApp;

class Autoloader
{
private $directory;
private $prefix;
private $prefixLength;

/**
* @param string $baseDirectory Base directory where the source files are located.
*/
public function __construct($baseDirectory = __DIR__)
{
$this->directory = $baseDirectory;
$this->prefix = __NAMESPACE__ . '\\';
$this->prefixLength = strlen($this->prefix);
}

/**
* Registers the autoloader class with the PHP SPL autoloader.
*
* @param bool $prepend Prepend the autoloader on the stack instead of appending it.
*/
public static function register($prepend = false)
{
spl_autoload_register(array(new self, 'autoload'), true, $prepend);
}

/**
* Loads a class from a file using its fully qualified name.
*
* @param string $className Fully qualified name of a class.
*/
public function autoload($className)
{
if (0 === strpos($className, $this->prefix)) {
$parts = explode('\\', substr($className, $this->prefixLength));
$filepath = $this->directory.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $parts).'.php';

if (is_file($filepath)) {
require($filepath);
}
}
}
}

0 comments on commit 6a7a5cc

Please sign in to comment.