PSR-0和PSR-4自动加载机制及composer自动加载

  1. 区别主要为:PSR0支持下划线(为了兼容5.2以前的第三方包,当时还没有命名空间,都是以下划线来区分的),psr0中类名的下划线将会转化为目录层级和相应的命名空间,如一个叫Swift_mail的类名存在于./Swift/Mail.php文件中,并且命名空间为当前命名空间\Swift.
  2. 自动加载机制用的最多的便是composer。下面以workman为例,详解composer的使用方式:
    • 在项目目录下执行composer require workerman/workerman
    • vendor目录结构如下图:
vendor/
├── autoload.php
├── composer
│   ├── autoload_classmap.php
│   ├── autoload_namespaces.php
│   ├── autoload_psr4.php
│   ├── autoload_real.php
│   ├── ClassLoader.php
│   ├── installed.json
│   └── LICENSE
└── workerman
    └── workerman
        ├── Autoloader.php
        ├── composer.json
        ├── Connection
        │   ├── AsyncTcpConnection.php
        │   ├── ConnectionInterface.php
        │   ├── TcpConnection.php
        │   └── UdpConnection.php
        ├── Events
        │   ├── EventInterface.php
        │   ├── Event.php
        │   ├── Ev.php
        │   ├── Libevent.php
        │   └── Select.php
        ├── Lib
        │   ├── Constants.php
        │   └── Timer.php
        ├── MIT-LICENSE.txt
        ├── Protocols
        │   ├── Frame.php
        │   ├── Http
        │   │   └── mime.types
        │   ├── Http.php
        │   ├── ProtocolInterface.php
        │   ├── Text.php
        │   ├── Websocket.php
        │   └── Ws.php
        ├── README.md
        ├── WebServer.php
        └── Worker.php
  • 对应的composer.json文件为:
    {
    "name" : "workerman/workerman",
    "type" : "project",
    "keywords": ["event-loop", "asynchronous"],
    "homepage": "http://www.workerman.net",
    "license" : "MIT",
    "description": "An asynchronous event driven PHP framework for easily building fast, scalable network applications.",
    "authors" : [
    {
    "name" : "walkor",
    "email" : "[email protected]",
    "homepage" : "http://www.workerman.net",
    "role": "Developer"
    }
    ],
    "support" : {
    "email" : "[email protected]",
    "issues": "https://github.com/walkor/workerman/issues",
    "forum" : "http://wenda.workerman.net/",
    "wiki" : "http://doc3.workerman.net/index.html",
    "source": "https://github.com/walkor/workerman"
    },
    "require": {
    "php": ">=5.3"
    },
    "suggest": {
    "ext-libevent": "For better performance."
    },
    "autoload": {
    "psr-4": {"Workerman\": "./"}
    },
    "minimum-stability":"dev"
    }

可以看出,vendor目录下面第一级为项目名workman/workman,在这层目录下面才是autoload里面注册的自动加载规则

  1. composer.json中的autoload四种方式介绍
  • classmap
    { "classmap": ["src/"]},会将src目录下的所有文件遍历生成map到vendor/composer/autoload_classmap.php中去
  • file(加载全局helper function)
    { "files": [ "path/to/file.php" ]}
  • psr-0
  • psr-4

http://feiyang.me/2012/05/php-psr-0-a-naming-standard/
https://psr.phphub.org/

你可能感兴趣的:(PSR-0和PSR-4自动加载机制及composer自动加载)