Reputation: 375
I am using a Factory class to manage the instantiation of objects and am passing into their constructors any dependency objects (Dependency Injection) e.g.
function createBasket() {
//pass in dependent objects
$apiCon = $this->createAPIConnector($this);
$basket = new Basket($this, $apiCon);
return $basket;
}
I am trying to avoid using the 'new' keyword within any classes (other than Factory), to allow simpler and more robust unit test, clearer code etc.
Now, my question relates to configuration values that many classes require e.g.
$apiURL = 'http://some.api.com';
$apiKey = 'abcde12345';
$adminEmail = '[email protected]';
These values remain constant for each application instance. I currently have them in a singleton class Config and they are reachable from within any class by the following:
$cfg = Config::getInstance();
$address = $cfg->apiURL;
However, this class instance is still a dependency within any Class that calls it, so should I think about passing this into class constructors, e.g.
function createBasket() {
//pass in dependent objects
$apiCon = $this->createAPIConnector($this);
$cfg = Config::getInstance();
//pass singleton config object to constructor
$basket = new Basket($this, $apiCon, $cfg);
return $basket;
}
...or perhaps pass them in via a set method, rather than via constructor:
function createBasket() {
//pass in dependent objects
$apiCon = $this->createAPIConnector($this);
$basket = new Basket($this, $apiCon);
//pass singleton config object to setter
$basket.setConfig(Config::getInstance());
return $basket;
}
Any guidance on the best approach would be much appreciated.
Thanks, James
Upvotes: 1
Views: 1265
Reputation: 680
Ive always seen them made as constants. I don't know that this is the "best" solution but I've seen this, and used it many times. Because its a const (the same is true for static vars, I would be interested to hear why one is better than the other) you don't need to instantiate the class which would probably save you some overhead if you want to be nit picky...
class SomeClass
{
const MYCONS = "APIKEY or Whateva";
}
then in when you need to use it require the file and do something like
SomeClass::MYCONST //to get your config info
Upvotes: 1
Reputation: 26
Seems like that defeats the purpose of having a singleton config object that's globally available. The entire point is to avoid having to pass it as a parameter to every class you make.
Upvotes: 1
Reputation: 7183
I use a similar method, setting everything up in a single array or file and defining it accordingly:
$config = array(
'MYCONST_1'=>'myValue',
'USER'=>'username',
'PASSWORD'=>'y3ahr1ght'
);
foreach($config as $const=>$value){
define($const,$value);
}
Upvotes: 0