In my application I have my constants:
define('APP_PATH', WEB_ROOT . APP_DIR);
define('LIBS_PATH', APP_PATH . LIBS_DIR);
define('MODELS_PATH', APP_PATH . MODELS_DIR);
define('VIEWS_PATH', APP_PATH . VIEWS_DIR);
define('CONTROLLERS_PATH', APP_PATH . CONTROLLERS_DIR);
etc...
because they will never be changing once my application starts and they are simple to access from within any class/method.
I have a config file too with other settings which gets imported into a $config
object that I pass around my application and retrieve them like:
$this->config->setting('some.setting');
I have never had to change a config value at the end or in the middle of my application so wouldn't it be easier to just define them as constants so I can access them anyway in my code easily?
I don't want to be statically retrieving settings either i.e
Config::setting('some.setting');
I have looked at the code of a few PHP frameworks and they all define paths as constants but then have other config settings in some sort of Config
class even though as far as I can see they never change those config settings throughout the code (they might though as I have not read through every line of the tens of thousands) and lots of those frameworks seem to love doing static calls to all sorts of methods from within methods in different classes and people say they are good frameworks but I've read and experienced more bad than good when it comes to static calls within classes/methods.
What do you think is best to do with the config settings? What do you do?
Wrapping constants in objects makes your code more portable.
This way you can load constants at application bootstrap from a file for example, so you can reuse your code in an arbitrary number of apps, each with a different configuration file.
To another extent, loading stuff from a class acts as a façade: you can move settings from a file to a database, to hardcoding them even, and the whole application won't notice.
You can go with define
for very little projects of course.
Wrapping settings in a config object provides encapsulation, which allows better coexistence.
For instance, suppose you have a framework for database access. If you used global settings for this, you couldn't easily access multiple databases in a single program. Putting the settings into an object allows you to use a particular config object for the corresponding database.