With a PHP MVC project, I have a few model classes that load data from a RESTful web service, which requires an API key. I’d like to store the necessary API key in the central config file of my application.
To get that API key to my class, which method would be considered best?
- Put the value in
$GLOBALS, so it can be accessed directly within the model classes which utilize it. - Pass the value to the class upon instantiation.
Method #2 seems best for OOP and code reuse, but method #1 is very convenient. I typically go with method #2, but I want to know if method #1 is generally considered to be an acceptable use of $GLOBALS, even in an OOP MVC environment.
Symfony 1.4 uses an sfConfig::get(‘my_value’), which is like your first option, only wrapped in an object.
Symfony 2 uses dependency injection to reduce coupling, which is like your second option. Make sure you check out this link for a good explanation on dependency injection.
However, reducing coupling increases complexity. So, it’s really a tradeoff. I think the main point is to be consistent in your application. Whichever method is used can be changed, so long as you’re consistent in its use.
I would pick dependency injection. Not only is it easy to use if you use it all of the time, it’s much more likely to lead to reusable code. The slowest part of a computer is the developer, so I try to build high quality, reusable components, wherever possible. I should also note that using dependency injection makes it much, much easier to build unit tests, should you choose to increase the quality and consistency of your code by adding unit tests.
Hope that helps…