【发布时间】:2011-10-12 14:22:23
【问题描述】:
我创建了一个如下所示的配置文件:
$conf['db_hostname'] = "localhost";
$conf['db_username'] = "username";
$conf['db_password'] = "password";
$conf['db_name'] = "sample";
$conf['db_type'] = "mysql";
$conf['db_prefix'] = "exp";
并将其保存为 config.php。
类似自动加载器的样子
class autoloader {
public static $loader;
public static function init()
{
if(self::$loader == NULL) {
self::$loader = new self();
}
return self::$loader;
}
public function __construct()
{
spl_autoload_register(array(this, 'library'));
spl_autoload_register(array(this, 'controller'));
spl_autoload_register(array(this, 'helper'));
spl_autoload_register(array($this, 'model'));
}
public function library($class)
{
set_include_path(get_include_path() . PATH_SEPARATOR . '/lib');
spl_autoload_extensions('.php');
spl_autoload($class);
}
public function controller($class)
{
set_include_path(get_include_path() . PATH_SEPARATOR . '/controller');
spl_autoload_extensions('.php');
spl_autoload($class);
}
public function helper($class)
{
set_include_path(get_include_path() . PATH_SEPARATOR . '/helper');
spl_autoload_extensions('.php');
spl_autoload($class);
}
public function model($class)
{
set_include_path(get_include_path() . PATH_SEPARATOR . '/model');
spl_autoload_extensions('.php');
spl_autoload($class);
}
}
- 我应该把这两个文件放在哪里?在根文件夹中?
- 这些
$configs 将如何在整个应用程序中可用? - 我应该如何在 index.php 中使用它们?我应该为
$config数组创建一个类吗? - 如何拒绝直接访问 config.php 文件?
【问题讨论】:
-
与你的问题无关,但如果你想让你的 Autoloader 成为单例,你应该降低
__construct()的可见性,所以你不得不使用autoloader::init()来获取唯一的实例。 -
对于您的配置文件,您可能需要查看:php.net/manual/en/function.parse-ini-file.php
标签: php bootstrapping autoloader