Blogger Information
Blog 29
fans 0
comment 0
visits 27277
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP基础:MVC利用服务容器统一管理外部对象
暴宇
Original
710 people have browsed it

PHP基础:MVC利用服务容器统一管理外部对象

1.代码示例

  1. <?php
  2. namespace mvc_demo;
  3. // 控制器依赖注入点改到构造方法, 实现对外部依赖对象的共享
  4. // 1. 加载模型类
  5. require 'Model.php';
  6. // 2. 加载视图
  7. require 'View.php';
  8. // 3. 服务容器
  9. class Container1
  10. {
  11. // 对象容器
  12. protected $instances = [];
  13. // 绑定: 向对象容器中添加一个类实例
  14. public function bind($alias, \Closure $process)
  15. {
  16. $this->instances[$alias] = $process;
  17. }
  18. // 取出: 从容器中取出一个类实例 (new)
  19. public function make($alias, $params = [])
  20. {
  21. return call_user_func_array($this->instances[$alias], []);
  22. }
  23. }
  24. $container = new Container1;
  25. // 绑定
  26. $container->bind('model', function () {return new Model;});
  27. $container->bind('view', function () {return new View;});
  28. // 3. 创建控制
  29. class Controller4
  30. {
  31. public function index(Container1 $container)
  32. {
  33. // 1. 获取数据
  34. $data = $container->make('model')->getData();
  35. // 2. 渲染模板/视图
  36. return $container->make('view')->fetch($data);
  37. }
  38. }
  39. // 客户端
  40. // 实例化控制器类
  41. $controller = new Controller4();
  42. echo $controller->index($container);
  43. //销毁对象
  44. unset($controller);

2.总结

在MVC模式下通过对外部对象的统一管理,让对象更易于维护。

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:容器的概念无处不在
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post