search
HomeBackend DevelopmentPHP TutorialFollow PSR-4 automatic loading, follow PSR-4 loading_PHP tutorial

Follow PSR-4 automatic loading, follow PSR-4 loading_PHP tutorial

Jul 13, 2016 am 10:10 AM
proppsrpsr-4onelearnloadofIntroductionautomaticwantfirst

遵循PSR-4的自动加载,遵循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循环中,会慢慢的缩短命名空间前缀的名称去需找合适的命名空间前缀,为什么要这么做呢?

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

Follow PSR-4 automatic loading, follow PSR-4 loading_PHP tutorial三、 例子

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

  --core

    -Autoload.php

  --vendor

    --test1

      -hello.php

    --test2

      -world.php

  -App.php

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/936671.htmlTechArticle遵循PSR-4的自动加载,遵循PSR-4加载 一、简介 首先这里要了解PSR,Proposing a Standards Recommendation(提出标准建议)的缩写,就是一种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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment