Service Locator He knows how to locate (create or acquire) the services that an application needs, and the service consumer does not need to care about the actual implementation of the service in real life. This article is mainly to share with you the PHP design mode of Service locator mode examples of detailed, I hope to help everyone.
What's the effect?
Decoupling service users and services without changing the code and simply configuring it to serve the service implementation.
UML diagram
code example
Class Servicelocator {/** * Service instance Index */privite $_services = []; /** * Service Definition Index */private $_definitions = []; /** * Whether global service sharing (Singleton mode) */Private $_shared = []; Public function has ($id) {return isset ($this->_services[$id]) | | isset ($this->_definitions[$id]); The 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])) {//instantiation $definition = $this->_definitio ns[$id]; $object = Creator::createobject ($definition);//Omit Service instantiation implementation if ($this->_shared[$id]) {$this->_ services[$id] = $object} return $object; } throw new Exception ("Unable to locate service {$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-&G t;_definitions[$id] = $definition; }} throw new Exception ("service add failed"); }}