php設計模式之服務定位器模式執行個體詳解

來源:互聯網
上載者:User
服務定位器(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("服務添加失敗");    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.