R
R
rumkin2011-02-20 23:48:52
PHP
rumkin, 2011-02-20 23:48:52

Using registry via wrapper without singleton in PHP?

How appropriate is the use of a similar construction for using the registry:

$___REGISTER = (object) array(); // Создаем StdClass для работы с массивом как с объектом

function &Reg()
{
    return $GLOBALS['___REGISTER'];
}

// Применение

Reg()->config = (object) array();
Reg()->config->host = 'habrahabr.ru';
Reg()->config->admin = '[email protected]';
Reg()->config->name = 'Хабрахабр';

// ... и т.д. и т.п.

I use to replace:
Register::set('config', array(/*... */));
$config = Register::get('config');

What pitfalls can be when using such a wrapper? Would you use such a wrapper in your projects? Where is it 100% not to be used?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
den1n, 2011-02-21
@den1n

I would not use it, because the global variable $___REGISTER can be accidentally or intentionally changed, and then look for where the “dog fumbled”.
If you really want to use stdClass as a container in the registry, then I would suggest doing this:

class Registry extends stdClass {
    private static $instance;

    private function __construct () {}
    private function __clone () {}

    public static function me ()
    {
        if (self::$instance === null)
            self::$instance = new self;
        return self::$instance;
    }
}

# Использовать так
Registry::me()->config = new stdClass;
Registry::me()->config->host = 'habrahabr.ru';
Registry::me()->config->admin = '[email protected]';
Registry::me()->config->name = 'Хабрахабр';

L
LoneCat, 2011-02-21
@LoneCat

You may well use the procedural php legacy for this purpose, namely the declaration of a static function variable .

function Reg() {
  static $registry = null;
  if(null === $registry) {
    $registry = new stdClass;
  }
  return $registry;
}

A
Alexey Shein, 2011-02-21
@conf

If you plan to test your own code (meaning automated, for example with PHPUnit), don't use singletons, let alone global variables (which you gave as an example). Read about testable design and the principle of Dependency Injection. If you read in English, I recommend this link misko.hevery.com/code-reviewers-guide/ and presentation
www.procata.com/talks/phptek-may2007-dependency.pdf
Here is a description of Symfony components translated into Russian : madbee.ukr.su/solenko/dependency-injection/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question