Using PHP classes to store configuration data
Join the DZone community and get the full member experience.Join For Free
; our conf.ini file
def_app = home
def_bck = main
def_fct = index
auth_adapter = nov\auth\def
driver = pgsql
dsn = "pgsql:dbname=pg1;host=localhost"
username = nov
password = nov
and now we use our ini file:
$conf = parse_ini_file("conf.ini", true);
another typical configuration file is xml . we also can use built-in functions within php when we want to parse xml files. there are also projects that use plain php files, and even yaml files (especially symfony users)
there are many standard options. why do i prefer a different one then? i like plain php classes because the ide helps me with autocompletion. the usage is quite simple. instead of using parse_ini_file function we only need to include our configuration class within our project.
const def_app = 'index';
const def_bck = 'index\bck\main\page';
const def_fct = 'init';
const auth_adapter = "nov\auth\def";
const db_pg1 = 'pg1';
const db_pg1_driver = 'pgsql';
const db_pg1_dsn = 'pgsql:dbname=pg1;host=localhost';
const db_pg1_username = 'nov';
const db_pg1_password = 'nov';
sometimes i want to use a variable stored into the application’s configuration but i don’t remember exactly the name of the variable. if i’ve got the configuration stored into a php array from a ini file (or xml, yaml, … ). i need to open the configuration file and find the name of the variable to use in my code. with a php class ides like netbeans of vim will pop up an autocompletion hint with the name of the variablean example of coding autocompletion with netbeans
and that’s all. maybe the worse part of this technique is if our application writes the configuration file (a typical installer.php). in this case we need to build the php’s class file and it’s slightly more complicated than writing a simple ini file.
what do you think about it? do you use another different way?
Published at DZone with permission of Gonzalo Ayuso, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.