2011-10-12 71 views
0

我創建一個配置文件,看起來像:如何使用配置文件和自動加載明智

$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); 
    } 
} 
  • 我應該在哪裏放置這兩個文件?在根文件夾中?
  • 這些$config將如何跨應用程序可用?
  • 我該如何在index.php中使用它們?我應該爲$config陣列創建一個類嗎?
  • 如何拒絕直接訪問config.php文件?
+0

與你的問題沒有關係,但是如果你想讓自動加載器成爲Singleton,你應該減少'__construct()'的可見性,所以你不得不使用'autoloader :: init()'來獲得只有它的實例。 – jprofitt

+0

爲你的配置文件,你可能想看看這個:http://php.net/manual/en/function.parse-ini-file.php – dqhendricks

回答

1

您必須包括您的配置文件。我會推薦使用require_once。將此代碼添加到任何需要配置變量的文件。最好的辦法是使用一個控制器文件,通常是一個index.php文件。這樣你只需要將require_once添加到單個文件。

require_once("./config.php"); 

不要擔心人看你的數據庫密碼,所有的PHP變量是純粹的服務器端,並沒有PHP代碼或變量可以通過客戶端來查看,除非明確地呼應了。

相關問題