Browse Source

Merge pull request #41 from thumbtack/autoloader

Add an autoloader class for Predis.
Daniele Alessandri 13 years ago
parent
commit
7ebbe25171
3 changed files with 43 additions and 8 deletions
  1. 3 0
      CHANGELOG
  2. 7 8
      README.markdown
  3. 33 0
      lib/Predis/Autoloader.php

+ 3 - 0
CHANGELOG

@@ -14,6 +14,9 @@ v0.7.0 (2010-xx-xx)
       - Predis\Client::setProfile()
         This method is no more part of the public API and has been made private.
 
+  * Predis now includes its own autoloader. To use it, include Autoloader.php
+    and call Predis\Autoloader::register().
+
   * The Predis\MultiBulkCommand class has been merged into Predis\Command and 
     thus removed. If you have code that extends Predis\MultiBulkCommand but 
     you can not afford to update your code, you can always implement it again 

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