user991047
user991047

Reputation: 315

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

    public function model($class)
    {
        set_include_path(get_include_path() . PATH_SEPARATOR . '/model');
        spl_autoload_extensions('.php');
        spl_autoload($class);
    }
} 

Upvotes: 1

Views: 3769

Answers (1)

lynks
lynks

Reputation: 5689

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.

Upvotes: 1

Related Questions