因此,Drupal使用一個基於Symfony2的依賴注入容器(DIC)來組織它的服務。依賴注入容器(DIC) - 如何處理過時的服務?
此外,我喜歡自己使用這種模式(使用更簡單和手工製作的解決方案)用於較小的項目。
簡化,它看起來像這樣:
class Container {
private $services = array();
function getService($key) {
if (isset($this->services[$key])) {
return $this->services[$key];
}
$method = 'create_' . $key;
// @todo Check if method exists.
// Call the method to lazy-create the service.
return $this->services[$key] = $this->$method($key);
}
function create_kitchen() {
// Kitchen depends on Stove.
$stove = $this->getService('stove');
return new Kitchen($stove);
}
function create_stove() {
return new Stove();
}
}
$container = new Container();
$kitchen = $container->getService('kitchen');
到目前爲止好。
但是如果我想用新的更換爐竈而不更換廚房呢?
$kitchen = $container->getService('kitchen');
$kitchen->cookAnEgg();
$container->replace('stove', new BetterStove());
$kitchen->cookAnEgg();
我需要一個機制來替換廚房爲好,讓老廚實例變得過時,或者我需要讓廚房知道爐子已被取代,因此第二個雞蛋可以用熟新的爐子。
如果廚房想要自己更換爐竈怎麼辦?
class Kitchen {
private $stove;
private $electrician;
function __construct(Stove $stove, Electrician $electrician) {
$this->stove = $stove;
$this->electrician = $electrician;
}
function cookAnEgg() {
while ($this->stove->isBroken()) {
$this->electrician->installNewStove();
}
..
}
}
廚房是怎麼知道新爐子的?
有沒有處理這種情況的最佳實踐?
我認爲使用觀察者模式的,但什麼是做,在組合與DIC的最佳做法?
編輯:
我正在把它作爲Symfony2,但我認爲它可以被看作是一個更普遍的問題,適用於各種依賴注入容器。
EDIT II:
擴展的例子。
Drupal 8中的一個典型例子是,如果語言發生變化,並且很多現有服務仍然使用舊語言。 – donquixote