服務定位器(service locator)他知道如何定位(建立或者擷取)一個應用所需要的服務,服務使用者在實際使用中無需關心服務的實際實現。本文主要和大家分享php設計模式之服務定位器模式執行個體詳解,希望能協助到大家。
有什麼作用
實現服務使用者和服務的解耦,無需改變代碼而只是通過簡單配置更服服務實現。
UML圖示
程式碼範例
class ServiceLocator { /** * 服務執行個體索引 */ privite $_services = []; /** * 服務定義索引 */ private $_definitions = []; /** * 是否全域服務共用(單例模式) */ private $_shared = []; public function has($id){ return isset($this->_services[$id]) || isset($this->_definitions[$id]); } public function __get($id){ if($this->has($this->id)){ $this->get($id); } // another implement } public function get($id){ if(isset($this->_services[$id]) && $this->_shared[$id]){ return $this->_services[$id]; } if (isset($this->_definitions[$id])) { // 執行個體化 $definition = $this->_definitions[$id]; $object = Creator::createObject($definition);//省略服務執行個體化實現 if($this->_shared[$id]){ $this->_services[$id] = $object } return $object; } throw new Exception("無法定位服務{$id}") } public function set($id,$definition,$share = false){ if ($definition === null) { unset($this->_services[$id], $this->_definitions[$id]); return; } unset($this->_services[$id]); $this->_shared[$id] = $share; if (is_string($definition)) { return $this->_definitions[$id] = $definition; } if (is_object($definition) || is_callable($definition, true)) { return $this->_definitions[$id] = $definition; } if (is_array($definition)) { if (isset($definition['class'])) { return $this->_definitions[$id] = $definition; } } throw new Exception("服務添加失敗"); }}