0

I am trying to find a good practice for storing commonly shared object for my framework. Previously, I am using $GLOBALS for accessing those shared object. However, I find many articles on internet saying that using $GLOBALS is a bad practice and suggest using Registry Pattern.

However, I have difficult time seeing how Registry Pattern is a better solution than $GLOBALS. For example:

<?php
   $config = new Config();
   $config->autoAppPath(__DIR__);
   $config->option = ... // some value;
   $config->option2 = ... // some value;

   $db = new Database();

   Registry::set('config', $config);
   Registry::set('db', $db);
?>

I wonder how is accessing using Registry is better than using GLOBALS asides from it has a better namespace?

Registry::get('config');
$GLOBALS['config'];
invisal
  • 11,075
  • 4
  • 33
  • 54
  • possible duplicate of [Registry design pattern...good or bad?](http://stackoverflow.com/questions/1151341/registry-design-pattern-good-or-bad) –  Aug 30 '13 at 11:46
  • @TimCooper, I have read that question before I ask this question. I think it is different because one talks if 'registry pattern' is bad or good. This question is what make 'registry pattern' better than $GLOBALS. – invisal Aug 30 '13 at 11:49

1 Answers1

1

I'm not sure what the Registry aims to fix here, it looks like a glorified global.

What you should look into is Dependency Injection. You wont have immediate benefits in your code but it really shines when you want to test your code. If you're using globals you can't unit-test your code because you can't mock anything.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • I am not sure myself either. I just thought maybe there are some hidden values of using it. If there is no further answer in (1 hour), I will mark this as answer. Thanks. – invisal Aug 30 '13 at 12:00
  • 1
    This Registry class can easily be mocked too. – Sherlock Aug 30 '13 at 12:05