this is more a conceptual question. Consider you have a php framework that runs a generic website.
You can of course tweak the framework behavior with settings, the question is: where is more natural to place these settings开发者_如何学运维?
My framework consists of some functions that helps me doing some tasks (for example cache managment).
In this fw I use a generic variable
$config = array( 'setting1'=>'value1' etc );
And if a function needs it does a global
:
function manageCache() {
global $config;
//> perform task with settings from $config
}
Consider the procedural nature of my framework, and the fact someone says global is evil
, how would you manage the settings?
Thanks
Edit1: Please don't tell to use constats, i have tons of settings and i don't want to make a tons of constant + they must be editable
There's nothing wrong with your configuration array. It's quite a common approach. The fallacy globals are evil
is cargo cult programming advise. Please ignore.
Now the $config
array is often easy to use by itself. But you can expand on that. It's quite simple for example to turn it into an ArrayObject once initialized:
$config = new ArrayObject($config, 2);
This will allow you to access the settings as $config["setting"]
and $config->setting
alike. It's easier on the eyes.
If you also want to avoid having to import the array everywhere, because you sometimes need just a single value, then expand with a wrapper function config("setting")
for convenience.
Btw, I'm usually using a mix of config array and constants myself. And I made a little management tool for plugins and a settings array in a central config.php
. http://web135.srv3.sysproserver.de/milki.erphesfurt.de./genericplugins/genconfig.html
If your settings are constant and do not change then consider using define()
- http://php.net/manual/en/function.define.php
//Set anywhere like this
define("DB_NAME", "stackoverflow");
// You can then read it from anywhere using
echo DB_NAME;
Is they need to be editable then you can use globals
, but ensure that register_globals
is off.
If you are using PHP5 then you could implement the Registry pattern to do this.
I'd be tempted to use a define rather than a variable, as this would at least remove the need for global variables.
That said, you can't (easily) store complex data types such as arrays via defines, so you'll want to factor this in.
Pass the global as a parameter of function
manageCache($config);
Globals are really evil
Normally you would have a config folder somewhere in your framework that you auto include on startup.
It would potentially look like this:
ROOT/
config/
db.php
cache.php
constants.php
You would then have something like a Config class that handles importing this configuration variables and converting them into instance variables. This way you can access these configuration variables like this:
$config->get_config('settings_1');
精彩评论