*Plik Bootstrap* Każdemu obiektowi który ma mieć zakres globalny przekazujemy w konstruktorze context
<?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 $context = array();
public function __construct(Context $context)
{
$this->context = $context->getRegistry();
$context->register($this);
}
public function __get($key)
{
if(isset($this->context[$key])) { return $this->context[$key];
}
}
}
?>
Obiekt Kontext
<?php
class Context
{
private $registry = array();
public function __get($key)
{
if(isset($this->registry[$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
print $user->config->test; // jak widac obiekt wyswietla zmienna z innego obiektu $log->config->test = 'foo'; // a zupelnie inny obiekt modyfikuje ta wartosc
print $user->config->test; // no i wartosc ulega zmienie tak jakby byla globalna ?>
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 @_@
Ten post edytował Black-Berry 5.11.2008, 09:24:28