<?php $context = new Context(); $config = new Config($context); $log = new Log($context); $dbDriver = new Db_Driver($context); $session = new Session($context); $language = new Language($context); $user = new User($context); $structure = new Structure($context); $router = new Router($context); $buffer = new Buffer($context); ?>
Każdy obiekt globalny dziedziczy po klasie System_Object
<?php class System_Object { public function __construct(Context $context) { $this->context = $context->getRegistry(); $context->register($this); } public function __get($key) { return $this->context[$key]; } } } ?>
Obiekt Kontext
<?php class Context { public function __get($key) { return $this->registry[$key]; } } public function register(System_Object $object) { $key = System_Strings::variableNotation(get_class($object)); $this->registry[$key] = $object; } public function getRegistry() { return $this->registry; } } ?>
Przykłądowa klasa. Wszystkie inne na podobnej zasadzie. Nie ma żadnych setterów, getterów, wszystko bez zbędnych kodów.
<?php class Config extends System_Object { public $test = 'Wartość testowa'; public function __construct(Context $context) { parent::__construct($context); } } ?>
sposób użycia
<?php $log->config->test = 'foo'; // a zupelnie inny obiekt modyfikuje ta wartosc ?>
Moim zdaniem to musi być ostateczne rozwiązanie problemu globalsów. Bardzo proszę o dyskusję
Czy singletony zamiast tego byłyby wydajniejsze ? Podobno singletony to zło. Ja już zgupłem do reszty @_@