Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should i store settings variables in php?

I am currently writing a program in php. I want to let the user of my script change some settings, like database location and user. These variable are placed on the first lines of the script.

Now i want to access these variables from everywhere of the script like in classes and functions.

I used globals for this. But a colleague told me not to use globals.

So what is the common way to store and access settings in php?

like image 737
Shylux Avatar asked Dec 05 '11 10:12

Shylux


2 Answers

You could use constants which are global by default:

define('APPLICATION_SETTING', true);

Otherwise you could use a Registry Singleton class in which you load the settings and store them in a class private variable. Classic Registry class structure:

class Registry {
    private $instance = NULL;
    private $vars = array();
    private __construct() {/**/}
    public static function getInstance() {/**/}
    public function get($key) {/**/}
    public function set($key, $value) {/**/}
}

And no, I suggest you not to use Injections and stuff patterns. Just use Singleton. With Injection you get everything worse and more complicated.

like image 52
Shoe Avatar answered Sep 25 '22 19:09

Shoe


Configuring a script by changing the variables inside the script is a bad idea.

The simplest way to store config setting is by using a .ini file and parse it with the parse_ini_file function. http://php.net/manual/en/function.parse-ini-file.php

sample ini:

[db]
host = "foo.org"
user = "dbguy"

[session]
timeout = 600

If your script is object oriented you should wrap the config setting in a class ... and pass it as a constructor argument to your main class.

Else you can use the global array but please do not use the 'global' keyword in your functions! your functions should accept settings from your functions as parameters.

$config = parse_ini_file("protectedFolder/config.ini", true);

//wrong, do not do it this way
function connect(){
  global $config;
  $connection = dostuff($config['db']['user'],$config['db']['host'];
  //do stuff
}

connect();

//right
function connect2($user, $host){
  $connection = dostuff($user, $host);
  //do stuff
}

connect2($config['db']['user'], $config['db']['host']);

This is a very simple concept, and there a better ways to do this, but it should get you started and it will do the job for simple apps.

If you need something more sophisticated you should google for "dependency injection"

EDIT: edited comments EDIT2: fixed missing quotes

like image 39
Oliver A. Avatar answered Sep 22 '22 19:09

Oliver A.