Blogger Information
Blog 32
fans 2
comment 0
visits 27916
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实例演示comoser.json的autoload字段的files, classmap, psr-4
简行
Original
712 people have browsed it

### 实例演示comoser.json的autoload字段的files, classmap, psr-4

文件地址:vendor文件夹部分是通过composer下载)

一.公用代码

1.Model.php代码:

  1. <?php
  2. namespace app\controller;
  3. class Model{
  4. public static function getData(){
  5. return "这是".__METHOD__."的数据!!!";
  6. }
  7. }

2.Goods.php代码:

  1. <?php
  2. namespace api;
  3. class Goods
  4. {
  5. public static function getData(){
  6. return "这是".__METHOD__."的数据";
  7. }
  8. }

3.index.php代码:

  1. <?php
  2. //加载composer的authload.php文件
  3. require __DIR__."/vendor/autoload.php";
  4. //取别名
  5. use app\controller\Model;
  6. use api\Goods;
  7. //客户端调用
  8. echo Model::getData();
  9. echo "<hr>";
  10. echo Goods::getData();
一.composer.json文件的files, classmap, psr-4写法演示

1.files:可以加载任意位置的类文件

  1. {
  2. "autoload": {
  3. "files": [
  4. "app/controller/Model.php",
  5. "api/Goods.php"
  6. ]
  7. }
  8. }

2.classmap:类映射 , 实现类的批量注册

  1. {
  2. "autoload": {
  3. "classmap": ["app/controller", "api"]
  4. }
  5. }

3.psr-4:格式要以(类的命名空间: 类所在的路径目录) 进行绑定, 命名空间最后必须以”\\”空间分隔符结尾

备注:符合psr-4规范

  • 类的命名空间与当前类文件的路径完全一致
  • 类名称与类文件的名称完全一致
  1. {
  2. "autoload": {
  3. "psr_4": {
  4. "app\\controller\\": "app/controller",
  5. "api\\": "api"
  6. }
  7. }
  8. }

总结

1.每次编辑完composer.json中的autoload字段的内容后, 就必须在终端执行composer dumpautoload才能生效

2.classmap:写法避免同一路径下的类文件的路径重复编写,减少代码量

3.psr-4:比较符合商业规范写法,且容易查找命名空间和文件地址

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:composer内容并不多, 也不难
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