【问题标题】:How to use config file and autoloader wisely如何明智地使用配置文件和自动加载器
【发布时间】: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


【解决方案1】:

您必须包含您的配置文件。我建议使用 require_once。将此代码添加到需要配置变量的任何文件中。最好的方法是使用控制器文件,通常是 index.php。这样你只需要将 require_once 添加到单个文件中。

require_once("./config.php");

不用担心别人会查看你的数据库密码,所有 php 变量都是纯服务器端的,除非明确回显,否则客户端无法查看任何 php 代码或变量。

【讨论】:

    猜你喜欢
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 2014-03-05
    相关资源
    最近更新 更多