我正嘗試構建自己的內部使用框架。 我得到的結構是這樣的:PHP:使用命名空間自動加載多個類
index.php
boot/
booter.php
application/
controllers/
indexcontroller.php
core/
template.class.php
model.class.php
controller.class.php
cache/
memcached.php
something/
something.php
Booter.php包含:(目前只有與位於核心目錄中的文件工作):
class Booter
{
private static $controller_path, $model_path, $class_path;
public static function setDirs($controller_path = 'application/controllers', $model_path = 'application/models', $classes_path = 'core')
{
self::$controller_path = $controller_path;
self::$model_path = $model_path;
self::$class_path = $classes_path;
spl_autoload_register(array('Booter', 'LoadClass'));
if (DEBUG)
Debugger::log('Setting dirs...');
}
protected static function LoadClass($className)
{
$className = strtolower($className);
if (file_exists(DIR . '/' . self::$model_path . '/' . $className . '.php'))
{
require(DIR . '/' . self::$model_path . '/' . $className . '.php');
}
else if (file_exists(DIR . '/' . self::$class_path . '/' . $className . '.class.php'))
{
require(DIR . '/' . self::$class_path . '/' . $className . '.class.php');
}
else if (file_exists(DIR . '/' . self::$controller_path . '/' . $className . '.php'))
{
require(DIR . '/' . self::$controller_path . '/' . $className . '.php');
}
if (DEBUG)
Debugger::log('AutoLoading classname: '.$className);
}
}
我的應用程序/控制器/索引控制器看起來是這樣的:
<?
class IndexController extends Controller
{
public function ActionIndex()
{
$a = new Model; // It works
$a = new Controller; //It works too
}
}
?>
這裏來我的問題:
[問題1]
我的代碼工作目前是這樣的:
$a = new Model; // Class Model gets included from core/model.class.php
我怎樣才能實現,包括通過使用命名空間的類文件?例如:
$a = new Cache\Memcached; // I would like to include file from /core/CACHE/Memcached.php
$a = new AnotherNS\smth; // i would like to include file from /core/AnotherNS/smth.php
等等。我怎樣才能產生處理命名空間?
[問題2]
的是它使用的類,控制器和模型或者我應該定義具有3個不同的方法,爲什麼3個不同的spl_autoload_register單自動加載一個好的做法呢?