开发者

How to use config file and autoloader wisely

开发者 https://www.devze.com 2023-04-12 18:01 出处:网络
I have created a config file that looks like: $conf[\'db_hostname\'] = \"localhost\"; $conf[\'db_username\'] = \"username\";

I have created a config file that looks like:

$conf['db_hostname'] = "localhost";
$conf['db_username'] = "username";
$conf['db_password'] = "password";
$conf['db_name'] = "sample";
$conf['db_type'] = "mysql";
$conf['db_prefix'] = "exp";

and saved it as config.php.

Similarly the autoloader looks like

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);
    }

开发者_StackOverflow    public function model($class)
    {
        set_include_path(get_include_path() . PATH_SEPARATOR . '/model');
        spl_autoload_extensions('.php');
        spl_autoload($class);
    }
} 
  • Where should I place both these files? In Root folder?
  • How these $configs will be available across the application?
  • How whould I use them in index.php? Should I create for $config array also a class?
  • How may I deny direct access to config.php file?


You must include your config file. I would recommend using require_once. Add this code to any files that will need the config variables. The best way to do this is to use a controller file, usually an index.php. That way you only need to add the require_once to a single file.

require_once("./config.php");

Don't worry about people viewing your database password, all php variables are purely server-side, and no php code or variables can be viewed by a client unless explicitly echoed out.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号