search
HomeBackend DevelopmentPHP TutorialAn example of file autoload following PSR-4

一、简介

  首先这里要了解PSR,Proposing a Standards Recommendation(提出标准建议)的缩写,就是一种PHP开发规范,让我们研发出来的代码更合理、更好维护、可读性更高。PSR有下面几个标准:

  •   PSR-0:自动加载
  •   PSR-1:基本代码规范
  •     PSR-2:代码样式
  •   PSR-3:日志接口
  •   PSR-4:规范自动加载的路径问题

  这里看出PSR的下标也是从0开始的,和数组还有点像~。其实PSR-4和PSR-0是有点相似甚至冗余的,他们都说明的是自动加载的规范,只不过PSR-4中的规范更加简洁,在PSR-0中下划线"_"是有特殊含义的,在autoload处理的时候需要将下划线转换为目录分隔符,而在PSR-4中下划线是没有任何特殊含义的,所以在文件自动加载的时候显得更加简洁、调理更加清楚。

  我对github上面的psr-4规范中的例子进行了大概的翻译(相信你们的英语水平一定比我好,肯定可以看懂^_^),然后以这个自动加载类库做了一个小小的例子,例子文件多、长,放在这里不太合适,所以我在博客中就大概介绍下这个例子,想要详细了解的可以去我的github主页去看这个例子。

二、 自动加载类库介绍

  首先看下自动加载类的大概内容:

<span>class</span><span> Autoload

  {
    </span><span>//</span><span> 注册自动加载函数到spl autoload栈中.</span>
     <span>public</span> <span>function</span><span> register();

    </span><span>//</span><span> 添加一个目录到一个命名空间前缀中</span>
    <span>public</span> <span>function</span> addNamespace(<span>$prefix</span>, <span>$base_dir</span>, <span>$prepend</span>=<span>false</span><span>);

    </span><span>//</span><span> 自动加载函数,会在$this->register中用到</span>
    <span>public</span> <span>function</span> loadClass(<span>$class</span><span>);

    </span><span>//</span><span> 寻找映射的文件</span>
    <span>public</span> <span>function</span> loadMappedFile(<span>$prefix</span>, <span>$relative_class</span><span>);

    </span><span>//</span><span>查看一个文件是否在文件系统中存在</span>
    <span>public</span> <span>function</span> requireFile(<span>$file</span><span>);

  }</span>

  自动加载类库函数中就这几个函数,其中register()、addNamespace()、loadMappedFile()、requireFile()函数都比较简单,一看就懂,唯一一个可能需要解释下的函数就是loadClass函数,先看下loadClass()函数的代码:

<span> 1</span>     <span>public</span> <span>function</span> loadClass(<span>$class</span><span>)
</span><span> 2</span> <span>    {
</span><span> 3</span>         <span>//</span><span> 当前的命名空间前缀</span>
<span> 4</span>         <span>$prefix</span> = <span>$class</span><span>;
</span><span> 5</span>         
<span> 6</span>         <span>//</span><span>通过命名空间去查找对应的文件</span>
<span> 7</span>         <span>while</span> (<span>false</span> !== <span>$pos</span> = <span>strrpos</span>(<span>$prefix</span>, '\\'<span>)) {
</span><span> 8</span>             
<span> 9</span>             <span>//</span><span> 可能存在的命名空间前缀</span>
<span>10</span>             <span>$prefix</span> = <span>substr</span>(<span>$class</span>, 0, <span>$pos</span> + 1<span>);
</span><span>11</span> 
<span>12</span>             <span>//</span><span> 剩余部分是可能存在的类</span>
<span>13</span>             <span>$relative_class</span> = <span>substr</span>(<span>$class</span>, <span>$pos</span> + 1<span>);
</span><span>14</span> 
<span>15</span>             <span>//</span><span>试图加载prefix前缀和relitive class对应的文件</span>
<span>16</span>             <span>$mapped_file</span> = <span>$this</span>->loadMappedFile(<span>$prefix</span>, <span>$relative_class</span><span>);
</span><span>17</span>             <span>if</span> (<span>$mapped_file</span><span>) {
</span><span>18</span>                 <span>return</span> <span>$mapped_file</span><span>;
</span><span>19</span> <span>            }
</span><span>20</span> 
<span>21</span>             <span>//</span><span> 移动命名空间和relative class分割位置到下一个位置</span>
<span>22</span>             <span>$prefix</span> = <span>rtrim</span>(<span>$prefix</span>, '\\'<span>);   
</span><span>23</span> <span>        }
</span><span>24</span>         
<span>25</span>         <span>//</span><span> 未找到试图加载的文件</span>
<span>26</span>         <span>return</span> <span>false</span><span>;
</span><span>27</span>     }

  其实有疑惑的地方可能也只有一个,那就是为什么这里要循环着去试图查找文件,在while循环中,会慢慢的缩短命名空间前缀的名称去需找合适的命名空间前缀,为什么要这么做呢?

  循环查找文件是为了在命名空间中包含更多的内容,不用每次在父命名空间中新建一个文件夹的时候都去添加一个新的命名空间前缀,就像下面这个图中描述的那样:

  当一个文件在一个命名空间下的子目录下的时候,我们不用去新建命名空间前缀就可以成功加载需要的文件,维护命名空间前缀的数组内容更少,更好维护。相反的如果没有循环查找,就是下面这个样子的

  

  每次新建一个子目录就要去新加一个命名空间前缀,是不是很麻烦,但这样的话也有一定的好处,就是加载的时候不晕循环查找文件,可能会减小一定的时间消耗,但就是加载的时候有点麻烦。

  所以,用循环加载这种方式还是比较方便的,但是一定不能让没有命名空间前缀的目录层级太深,这样会消耗不必要的时间到文件加载上。当需要效率很高的时候,而我们的目录肯定又不会不确定,这个时候加载的时候去掉循环查找,而是为每个目录添加命名空间,效率可能会提高,只是我的一点愚见。

三、 例子

  说道这里你可能已经对自动加载的内容比较了解了,这个时候趁热打铁看看我准备的小例子,这里只是介绍下小例子的目录结构,由于比较简单,详细的内容就不再这里列了,感兴趣的通许可以去我的github主页看看这个例子

  --core

    -Autoload.php

  --vendor

    --test1

      -hello.php

    --test2

      -world.php

  -App.php

  本文版权归作者(luluyrt@163.com)和博客园共有,未经作者本人同意禁止任何形式的转载,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。

以上就介绍了一个遵循PSR-4的文件autoload的例子,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.