How to use config file and autoloader wisely
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
$config
s 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.
精彩评论