接上回的继续说,上回说到PSR-3日志记录器接口,这回我们来说说PSR的最后一个标准,PSR-4,自动加载器策略。

缘由

自动加载器策略是指,在运行时按需查找PHP类、接口或性状,并将其载入PHP解释器。

支持PSR-4自动加载器标准的PHP组件和框架,使用同一个自动加载器就能找到相关代码,然后将其载入PHP解释器。

怎么来理解呢,你可能看PHP代码的时候经常会看到下面的代码

<?php
include 'path/to/file1.php';
include 'path/to/file2.php';
include 'path/to/file3.php';

如果需要引入一百个,一千个PHP脚本,include()函数就不能胜任了。有了自动加载器,我们就无需这样引入文件,自动加载器策略能找到PHP类、接口或性状,然后在运行时按需将其载入PHP解释器。

大多数现代的PHP组件和框架都符合PSR-4规范,如果你要自己编写并分发PHP组件,确保你的组件也符合PSR-4规范。

PSR-4

1、The term “class” refers to classes, interfaces, traits, and other similar structures.

2、A fully qualified class name has the following form:

 \<NamespaceName>(\<SubNamespaceNames>)*\<ClassName>

The fully qualified class name MUST have a top-level namespace name, also known as a “vendor namespace”.

The fully qualified class name MAY have one or more sub-namespace names.

The fully qualified class name MUST have a terminating class name.

Underscores have no special meaning in any portion of the fully qualified class name.

Alphabetic(按字母排序的) characters in the fully qualified class name MAY be any combination of lower case and upper case.

All class names MUST be referenced in a case-sensitive fashion.

3、When loading a file that corresponds to a fully qualified class name …(加载完整路径类名)

A contiguous series of one or more leading namespace and sub-namespace names, not including the leading namespace separator, in the fully qualified class name (a “namespace prefix”) corresponds to at least one “base directory”.

The contiguous sub-namespace names after the “namespace prefix” correspond to a subdirectory within a “base directory”, in which the namespace separators represent directory separators. The subdirectory name MUST match the case of the sub-namespace names.

The terminating class name corresponds to a file name ending in .php. The file name MUST match the case of the terminating class name.

4、Autoloader implementations MUST NOT throw exceptions, MUST NOT raise errors of any level, and SHOULD NOT return a value.

例子

    FULLY QUALIFIED CLASS NAME     NAMESPACE PREFIX     BASE DIRECTORY     RESULTING FILE PATH
    \Acme\Log\Writer\File_Writer     Acme\Log\Writer     ./acme-log-writer/lib/     ./acme-log-writer/lib/File_Writer.php
    \Aura\Web\Response\Status     Aura\Web     /path/to/aura-web/src/     /path/to/aura-web/src/Response/Status.php
    \Symfony\Core\Request     Symfony\Core     ./vendor/Symfony/Core/     ./vendor/Symfony/Core/Request.php
    \Zend\Acl     Zend     /usr/includes/Zend/     /usr/includes/Zend/Acl.php

PSR-4的精髓是把命名空间的前缀和文件系统中的目录对应起来。例如,我可以告诉PHP,\Feng\YePHP命名空间中的类、接口和性状在物理文件系统的src/目录中,这样PHP就知道,前缀为\Feng\YePHP的命名空间中的类、接口和性状对应于src/目录里的目录和文件。

如何编写

<?php
/**
* An example of a project-specific implementation.
*
* After registering this autoload function with SPL, the following line
* would cause the function to attempt to load the \Foo\Bar\Baz\Qux class
* from /path/to/project/src/Baz/Qux.php:
*
* new \Foo\Bar\Baz\Qux;
*
* @param string $class The fully-qualified class name.
* @return void
*/
spl_autoload_register(function ($class) { // project-specific namespace prefix
$prefix = 'Foo\\Bar\\'; // base directory for the namespace prefix
$base_dir = __DIR__ . '/src/'; // does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// no, move to the next registered autoloader
return;
} // get the relative class name
$relative_class = substr($class, $len); // replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php'; // if the file exists, require it
if (file_exists($file)) {
require $file;
}
});

复制以上代码,将其粘贴到你的应用中,然后修改变量$prefix和$base_dir的值,这样你就可以拥有一个可用的PSR-4自动加载器了。

但是你大可不必这么做,因为我们可以使用依赖管理器Composer自动生成的PSR-4自动加载器。我们会在后续的博文中提及这个Composer。

【PHP系列】PHP推荐标准之PSR-4,自动加载器策略的更多相关文章

  1. 【PSR规范专题(5)】PSR-4 改进后的自动加载规范

    本文转自: https://github.com/PizzaLiu/PHP-FIG/blob/master/PSR-4-autoloader-cn.md 关键词 "必须"(&quo ...

  2. thinkphp5源码剖析系列1-类的自动加载机制

    前言 tp5想必大家都不陌生,但是大部分人都停留在应用的层面,我将开启系列随笔,深入剖析tp5源码,以供大家顺利进阶.本章将从类的自动加载讲起,自动加载是tp框架的灵魂所在,也是成熟php框架的必备功 ...

  3. 【SpringBoot 基础系列】实现一个自定义配置加载器(应用篇)

    [SpringBoot 基础系列]实现一个自定义配置加载器(应用篇) Spring 中提供了@Value注解,用来绑定配置,可以实现从配置文件中,读取对应的配置并赋值给成员变量:某些时候,我们的配置可 ...

  4. 如何实现一个php框架系列文章【3】支持psr4的自动加载类

    psr4自动加载规范https://github.com/PizzaLiu/PHP-FIG/blob/master/PSR-4-autoloader-cn.md 我们把第三方使用psr规范的类库放在v ...

  5. PHP 自动加载的简单实现(推荐)

    基于psr的规范,使用命名空间和spl_autoload_register()来实现自动加载 文件结构: |--Api |--Account.php |--User.php |--Service |- ...

  6. PHP系列 | ThinkPHP5.1 如何自动加载第三方SDK(非composer包 )

    注意:这里只是针对于非Composer 安装包的自动加载的实现,能用composer安装的自动跳过. 由于ThinkPHP5.1 严格遵循PSR-4规范,不再建议手动导入类库文件,所以新版取消了Loa ...

  7. Android批量图片加载经典系列——afinal框架实现图片的异步缓存加载

    一.问题描述 在之前的系列文章中,我们使用了Volley和Xutil框架实现图片的缓存加载(查看系列文章:http://www.cnblogs.com/jerehedu/p/4607599.html# ...

  8. Google推荐——Glide使用详解(图片加载框架)

    零.前言 本文所使用的Glide版本为3.7.0 一.简介 Glide,一个被google所推荐的图片加载库,作者是bumptech.这个库被广泛运用在google的开源项目中,包括2014年的goo ...

  9. 《Entity Framework 6 Recipes》中文翻译系列 (43) ------ 第八章 POCO之使用POCO加载实体

    翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 8-2  使用POCO加载关联实体 问题 你想使用POCO预先加载关联实体. 解决方 ...

随机推荐

  1. js排序算法汇总

    JS家的排序算法   十大经典算法排序总结对比 一张图概括: 主流排序算法概览 名词解释: n: 数据规模k:“桶”的个数In-place: 占用常数内存,不占用额外内存Out-place: 占用额外 ...

  2. Django中扩展Paginator实现分页

    Reference:https://my.oschina.net/kelvinfang/blog/134342 Django中已经实现了很多功能,基本上只要我们需要的功能,都能够找到相应的包.要在Dj ...

  3. 七 APPIUM Android 定位方式

    1.定位元素应用元素   1.1通过id定位元素 Android里面定位的id一般为resrouce-id: 代码可以这样写: WebElement element = driver.findElem ...

  4. HTML5学习笔记 二:article和section

    在HTML5中,article可以看做特殊种类的section,它比section更强调独立性. section元素强调分段或分块,而article强调独立性: 如果一块内容相对独立.完整,应该使用a ...

  5. IOS 上线问题

    info.plist 是否支持后台位置 音频 Info.plist中添加UIBackgroundModes键值,它包含一个或多个string的值,包括 audio:在后台提供声音播放功能,包括音频流和 ...

  6. bzoj 3572世界树 虚树+dp

    题目大意: 给一棵树,每次给出一些关键点,对于树上每个点,被离它最近的关键点(距离相同被标号最小的)控制 求每个关键点控制多少个点 分析: 虚树+dp dp过程如下: 第一次dp,递归求出每个点子树中 ...

  7. [oracle]Oracle角色管理

    假如我们直接给每一个用户赋予权限,这将是一个巨大又麻烦的工作,同时也不方便DBA进行管理.通过采用角色,使得: 权限管理更方便.将角色赋予多个用户,实现不同用户相同的授权.如果要修改这些用户的权限,只 ...

  8. thinkphp 3.2 导入第三方类库的两种方式

    第一种

  9. [ Android 五种数据存储方式之二 ] —— 文件存储数据

    关于文件存储,Activity提供了openFileOutput()方法可以用于把数据输出到文件中,具体的实现过程与在J2SE环境中保存数据到文件中是一样的. 文件可用来存放大量数据,如文本.图片.音 ...

  10. HDFS存储系统

    HDFS存储系统 一.基本概念 1.NameNode HDFS采用Master/Slave架构.namenode就是HDFS的Master架构.主要负责HDFS文件系统的管理工作,具体包括:名称空间( ...