您好,欢迎访问一九零五行业门户网

php设计模式之服务定位器模式实例详解

服务定位器(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(服务添加失败);     } }
相关推荐:
详解php设计模式之委托模式
详解php设计模式之备忘录模式
详解php设计模式之建造者模式
以上就是php设计模式之服务定位器模式实例详解的详细内容。
其它类似信息

推荐信息