Skip to content

Commit 6ae4253

Browse files
committed
Fixed manual autoloader.
1 parent d371265 commit 6ae4253

File tree

4 files changed

+53
-38
lines changed

4 files changed

+53
-38
lines changed

README.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,7 @@ UserApp relies on the autoloading features of PHP to load its files when needed.
2424

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

27-
require 'lib/Autoloader.php';
28-
UserApp\Widget\Autoloader::register();
27+
require 'autoload.php';
2928

3029
## Example
3130

autoload.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<?php
2+
3+
require __DIR__.'/lib/UserApp/Widget/Autoloader.php';
4+
5+
UserApp\Widget\Autoloader::register();

lib/Autoload.php

Lines changed: 0 additions & 36 deletions
This file was deleted.

lib/UserApp/Widget/Autoloader.php

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<?php
2+
3+
namespace UserApp\Widget;
4+
5+
class Autoloader
6+
{
7+
private $directory;
8+
private $prefix;
9+
private $prefixLength;
10+
11+
/**
12+
* @param string $baseDirectory Base directory where the source files are located.
13+
*/
14+
public function __construct($baseDirectory = __DIR__)
15+
{
16+
$this->directory = $baseDirectory;
17+
$this->prefix = __NAMESPACE__ . '\\';
18+
$this->prefixLength = strlen($this->prefix);
19+
}
20+
21+
/**
22+
* Registers the autoloader class with the PHP SPL autoloader.
23+
*
24+
* @param bool $prepend Prepend the autoloader on the stack instead of appending it.
25+
*/
26+
public static function register($prepend = false)
27+
{
28+
spl_autoload_register(array(new self, 'autoload'), true, $prepend);
29+
}
30+
31+
/**
32+
* Loads a class from a file using its fully qualified name.
33+
*
34+
* @param string $className Fully qualified name of a class.
35+
*/
36+
public function autoload($className)
37+
{
38+
if (0 === strpos($className, $this->prefix)) {
39+
$parts = explode('\\', substr($className, $this->prefixLength));
40+
$filepath = $this->directory.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $parts).'.php';
41+
42+
if (is_file($filepath)) {
43+
require($filepath);
44+
}
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)