Created
January 25, 2012 10:19
-
-
Save k-holy/1675742 to your computer and use it in GitHub Desktop.
include_path前提のnamespace対応autoload実装
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme; | |
set_include_path(implode(PATH_SEPARATOR, array( | |
'/path/to/pear', | |
'/path/to/vendor', | |
get_include_path(), | |
))); | |
spl_autoload_register(function($className) { | |
$className = ltrim($className, '\\'); | |
if (false !== ($pos = strrpos($className, '\\'))) { | |
$namespace = substr($className, 0, $pos); | |
$className = substr($className, $pos + 1); | |
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) | |
. DIRECTORY_SEPARATOR | |
. str_replace('_', DIRECTORY_SEPARATOR, $className); | |
} else { | |
$fileName = str_replace('_', DIRECTORY_SEPARATOR, $className); | |
} | |
if (false !== ($path = stream_resolve_include_path($fileName . '.php'))) { | |
return include $path; | |
} | |
return false; | |
}, true, true); | |
$e = new \PEAR_Exception('GRRRR'); | |
$k1 = new \Acme\Klass(); | |
$k2 = new Klass(); | |
var_dump(get_class($e));// string(14) "PEAR_Exception" | |
var_dump(get_class($k1));// string(10) "Acme\Klass" | |
var_dump(get_class($k2));// string(10) "Acme\Klass" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/1318652 の続き
https://gist.github.com/1127033 が元ネタ
include_path前提のため、
/vendor/Hoge/src/Hoge/
/vendor/Hoge/tests/
といったディレクトリ構成の場合は使えませんが、ユニットテストの初期化スクリプトには便利かも