Answer the question
In order to leave comments, you need to log in
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 = 'Хабрахабр';
// ... и т.д. и т.п.
Register::set('config', array(/*... */));
$config = Register::get('config');
Answer the question
In order to leave comments, you need to log in
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 = 'Хабрахабр';
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;
}
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 questionAsk a Question
731 491 924 answers to any question