Blogger Information
Blog 45
fans 0
comment 0
visits 34499
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
php facade与composer的使用
咸鱼老爷
Original
667 people have browsed it

facade

在服务容器与工作类之间添加一个中间层,门面

  1. namespace mvc;
  2. use Closure;
  3. // 加载模型和视图
  4. require 'model.php';
  5. require 'view.php';
  6. // 服务容器
  7. class Container1{
  8. //对象容器
  9. protected $instances=[];
  10. // 添加对象
  11. public function bind($alias,Closure $process){
  12. $this->instances[$alias]=$process;
  13. }
  14. // 取出对象
  15. public function make($alias,$params=[]){
  16. return call_user_func_array($this->instances[$alias],[]);
  17. }
  18. }
  19. // 将依赖的外部对象添加到容器中
  20. $container=new Container1();
  21. $container->bind('model',function(){return new Model();});
  22. $container->bind('view',function(){return new View();});
  23. //--------------------
  24. // 在服务容器与工作类之间添加一个中间层,门面
  25. class Facade{
  26. protected static $container =null;
  27. //初始化
  28. public static function initialize(Container1 $container){
  29. static::$container=$container;
  30. }
  31. }
  32. class UsersModel extends Facade{
  33. public static function getData(){
  34. return static::$container->make('model')->getData();
  35. }
  36. }
  37. class UsersView extends Facade{
  38. public static function fetch($data){
  39. return static::$container->make('view')->fetch($data);
  40. }
  41. }
  42. //--------------------
  43. class Controller5
  44. {
  45. //构造器主要是为了facade门面的初始化
  46. public function __construct(Container1 $container)
  47. {
  48. Facade::initialize($container);
  49. }
  50. public function index()
  51. {
  52. $data = UsersModel::getData();
  53. return UsersView::fetch($data);
  54. }
  55. }
  56. // 客户端测试
  57. $controller = new Controller5($container);
  58. echo $controller->index();

调用代码更加简洁,使用方便且减少出错

composer 是什么

  • php 包依赖管理工具
  • 包: 组件,一组相关的类,接口,trait 的结合体
  • 依赖: A -> B -> C -> D
  • composer 就是用 php 语言开发的

组件放在了哪里

下载

常用指令

  • composer install: 安装 composer.josn 中的依赖
  • composer update: 更新依赖
  • composer selfupdate: 更新 composer 版本
  • composer require: 添加依赖到 composer.json 中
  • composer create-project: 安装项目

自动加载 autoload

  • 文件级: “files”, 需要将加载的文件逐个导入
  • 目录级: “classmap”,类目录的映射
  • 空间级: “psr-4”: 命名空间映射到目录
  • 无论是哪一种,最后都要执行一下”composer dump”,更新 composer.json 中的 autoload 配置项
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