tags:

views:

65

answers:

3

Hello,

On application start I'm creating Config object (Singleton). How could I make Config object be available inside Model and Controller? Should I pass Config object to constructor as method parametr or I should better use $this->config = Config::getInstance()? Any other methods?

Thank you

A: 

If Config is a Singleton, you can use pretty much any solution you'd like :

  • Passing it as a parameter is not needed, as it's global
    • But passing is as a parameter can allow for dependancy injection -- which might help if you want some automated tests
  • Storing it as a class property can be useful -- but it's not required either.


Generally, for that kind of object, I just use Config::getInstance() each time I need it, and don't store it in a class property.

But I guess this is a matter of personnal preferences...

Pascal MARTIN
A: 

I usually make it a instance singleton by means of Config::getInstance(), and add accesors in Environment#config (or Bootstrap#config , tutorials go with Bootstrap) and My_Top_Controller#config (this My_Top_Controller extends Zend_Controller and is the ancestor of all other controllers) and also add it to Zend_Registry via config key.

clyfe
+2  A: 

Singleton is essentially just fancy syntax for a global variable, and is as bad as globals are (and they are bad). Passing a parameter is the cleanest option as it creates no hard coupling between classes and allows for maximum flexibility. Another reasonable (but rather advanced) option is to use a dependency injection container, see for example this post.

stereofrog
Reading now your link - very interesting, especially this article http://www.sitepoint.com/blogs/2008/02/04/dealing-with-dependencies/ By the way, please could you tell me why globals are considered to be bad way?
Kirzilla
globals create dependencies in your code which are hard to follow. Like chasing someone who has a teleport wand.
stereofrog
...probably. I'm just starting to do some OOP in PHP.
Kirzilla