开发者

Using Registry class instead of Global variables. How to make it better

I am trying to create a better registry class, so I don't have to declare global variables like some database connections, using sensitive infor开发者_运维百科mation in a global variable.

Here is an idea which I found online in some tutorial. I would like to ask if it is OK, or we can make it better in some other way?

class registry {
    private $register = array();

     public function __set($index, $value)  {
        $this->register[$index] = $value;
     }
     public function __get($index)  {
        return $this->register[$index];
     }
}


Global variables are bad. It doesn't matter if you've independent variables, an object holding them, or if you store them in an associative array, or if you use one or more Singleton Objects to hold them. All parts of your application will have a dependency on those magic values and will be difficult to test.

The alternative is called dependency injection allows you to feed those configuration values to the class that actually need them, without putting them in the global state.

There are also other advantages of dependency injection, like decoupling of dependencies. In other words, classes that depend on other classes don't have to create the dependency themselves, thus hard-wiring them, but a framework can inject them for you (set them in the object).

There are many frameworks supporting dependency injection, among them:

  • Symphony
  • Yii
  • Zend
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜