当前位置:Gxlcms > PHP教程 > php设计模式之服务定位器模式实例详解

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

时间:2021-07-01 10:21:17 帮助过:3人阅读

服务定位器(service locator)他知道如何定位(创建或者获取)一个应用所需要的服务,服务使用者在实际使用中无需关心服务的实际实现。本文主要和大家分享php设计模式之服务定位器模式实例详解,希望能帮助到大家。

有什么作用

实现服务使用者和服务的解耦,无需改变代码而只是通过简单配置更服服务实现。

UML图示

代码示例

  1. class ServiceLocator {
  2. /**
  3. * 服务实例索引
  4. */
  5. privite $_services = [];
  6. /**
  7. * 服务定义索引
  8. */
  9. private $_definitions = [];
  10. /**
  11. * 是否全局服务共享(单例模式)
  12. */
  13. private $_shared = [];
  14. public function has($id){
  15. return isset($this->_services[$id]) || isset($this->_definitions[$id]);
  16. }
  17. public function __get($id){
  18. if($this->has($this->id)){
  19. $this->get($id);
  20. }
  21. // another implement
  22. }
  23. public function get($id){
  24. if(isset($this->_services[$id]) && $this->_shared[$id]){
  25. return $this->_services[$id];
  26. }
  27. if (isset($this->_definitions[$id])) {
  28. // 实例化
  29. $definition = $this->_definitions[$id];
  30. $object = Creator::createObject($definition);//省略服务实例化实现
  31. if($this->_shared[$id]){
  32. $this->_services[$id] = $object
  33. }
  34. return $object;
  35. }
  36. throw new Exception("无法定位服务{$id}")
  37. }
  38. public function set($id,$definition,$share = false){
  39. if ($definition === null) {
  40. unset($this->_services[$id], $this->_definitions[$id]);
  41. return;
  42. }
  43. unset($this->_services[$id]);
  44. $this->_shared[$id] = $share;
  45. if (is_string($definition)) {
  46. return $this->_definitions[$id] = $definition;
  47. }
  48. if (is_object($definition) || is_callable($definition, true)) {
  49. return $this->_definitions[$id] = $definition;
  50. }
  51. if (is_array($definition)) {
  52. if (isset($definition['class'])) {
  53. return $this->_definitions[$id] = $definition;
  54. }
  55. }
  56. throw new Exception("服务添加失败");
  57. }
  58. }

相关推荐:

详解PHP设计模式之委托模式

详解PHP设计模式之备忘录模式

详解PHP设计模式之建造者模式

以上就是php设计模式之服务定位器模式实例详解的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行