Question

If a class requires some xml configuration values in order to perform an action, which of the following is best:

  1. Pass config to constructor
  2. Do not pass config to constructor but instead load the xml in the constructor
  3. Pass an intermediary object which can load the required config
  4. Pass config to public method performing the action

I am currently going with option 3:

class MyClass
{
    private $config;

    const CONFIG_XML_PATH = '/xml/path/to/my/config/node'

    public function __construct($configLoader)
    {
        $this->config = $configLoader->load(self::CONFIG_XML_PATH)
    }

    public function doAmazingThingUsingConfig()
    {

    }

}

Is this the correct way to do this or is there a better way?

No correct solution

OTHER TIPS

My Suggestion

IMHO the class that needs to be constructed should not be responsible for creating and loading it's own dependencies.

The dependencies should be created outside the class and then passed to the class using any kind of dependency injection.

Also, the tests for such a class would be easier written and verified than in this case. Of course, here also you can write the tests by mocking the configLoader but why do it through mocking if we could do it through normal injection :-)

Suggestions For Your Approach

In case you really really want to go with your approach, then at least abstract out the config loading class to not use the file directly ( so that you can load the configuration in some other manner as well )

I would suggest to do away with const variable and change the function call to something like this:

$configLoader->loadMyClassConfig();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top