浏览代码

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>
Eric Naeseth 13 年之前
父节点
当前提交
94a2ddeca9
共有 2 个文件被更改,包括 40 次插入8 次删除
  1. 7 8
      README.markdown
  2. 33 0
      lib/Predis/Autoloader.php

+ 7 - 8
README.markdown

@@ -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 - 0
lib/Predis/Autoloader.php

@@ -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;
+    }
+}