Add an autoloader for Predis classes.

This makes it easier to use Predis in scripts and projects that do
not already include as PSR-0 autoloader.

Signed-off-by: Eric Naeseth <eric@thumbtack.com>
This commit is contained in:
Eric Naeseth
2011-09-27 17:33:26 -07:00
parent 45a5dd49a7
commit 94a2ddeca9
2 changed files with 40 additions and 8 deletions
+7 -8
View File
@@ -28,17 +28,16 @@ complete coverage of all the features available in Predis.
Predis relies on the autoloading features of PHP and complies with the
[PSR-0 standard](http://groups.google.com/group/php-standards/web/psr-0-final-proposal)
for interoperability with most of the major frameworks and libraries.
When used in simple projects or scripts you might need to define an autoloader function:
When used in a project or script without PSR-0 autoloading, Predis includes its own autoloader for you to use:
``` php
<?php
spl_autoload_register(function($class) {
$file = PREDIS_BASE_PATH . strtr($class, '\\', '/') . '.php';
if (file_exists($file)) {
require $file;
return true;
}
});
require PREDIS_BASE_PATH . '/Autoloader.php';
Predis\Autoloader::register();
// You can now create a Predis\Client, and use other Predis classes, without
// requiring any additional files.
```
You can also create a single [Phar](http://www.php.net/manual/en/intro.phar.php) archive from the repository
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace Predis;
class Autoloader {
private $base_directory;
private $prefix;
public function __construct($base_directory=NULL) {
$this->base_directory = $base_directory ?: dirname(__FILE__);
$this->prefix = __NAMESPACE__ . '\\';
}
public static function register() {
spl_autoload_register(array(new self, 'autoload'));
}
public function autoload($class_name) {
if (0 !== strpos($class_name, $this->prefix)) {
return;
}
$relative_class_name = substr($class_name, strlen($this->prefix));
$class_name_parts = explode('\\', $relative_class_name);
$path = $this->base_directory .
DIRECTORY_SEPARATOR .
implode(DIRECTORY_SEPARATOR, $class_name_parts) .
'.php';
require_once $path;
}
}