Table of Contents
遵循PSR-4的自动加载,遵循PSR-4加载
一、简介
二、 自动加载类库介绍
Home php教程 php手册 遵循PSR-4的自动加载,遵循PSR-4加载

遵循PSR-4的自动加载,遵循PSR-4加载

Jun 13, 2016 am 09:17 AM
prop psr psr-4 one learn load of Introduction automatic want first

遵循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>
Copy after login

  自动加载类库函数中就这几个函数,其中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>     }
Copy after login

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

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

三、 例子

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

  --core

    -Autoload.php

  --vendor

    --test1

      -hello.php

    --test2

      -world.php

  -App.php

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

Statement of this Website
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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Error loading plugin in Illustrator [Fixed] Error loading plugin in Illustrator [Fixed] Feb 19, 2024 pm 12:00 PM

When launching Adobe Illustrator, does a message about an error loading the plug-in pop up? Some Illustrator users have encountered this error when opening the application. The message is followed by a list of problematic plugins. This error message indicates that there is a problem with the installed plug-in, but it may also be caused by other reasons such as a damaged Visual C++ DLL file or a damaged preference file. If you encounter this error, we will guide you in this article to fix the problem, so continue reading below. Error loading plug-in in Illustrator If you receive an "Error loading plug-in" error message when trying to launch Adobe Illustrator, you can use the following: As an administrator

Stremio subtitles not working; error loading subtitles Stremio subtitles not working; error loading subtitles Feb 24, 2024 am 09:50 AM

Subtitles not working on Stremio on your Windows PC? Some Stremio users reported that subtitles were not displayed in the videos. Many users reported encountering an error message that said "Error loading subtitles." Here is the full error message that appears with this error: An error occurred while loading subtitles Failed to load subtitles: This could be a problem with the plugin you are using or your network. As the error message says, it could be your internet connection that is causing the error. So please check your network connection and make sure your internet is working properly. Apart from this, there could be other reasons behind this error, including conflicting subtitles add-on, unsupported subtitles for specific video content, and outdated Stremio app. like

Digital audio output interface on the motherboard-SPDIF OUT Digital audio output interface on the motherboard-SPDIF OUT Jan 14, 2024 pm 04:42 PM

SPDIFOUT connection line sequence on the motherboard. Recently, I encountered a problem regarding the wiring sequence of the wires. I checked online. Some information says that 1, 2, and 4 correspond to out, +5V, and ground; while other information says that 1, 2, and 4 correspond to out, ground, and +5V. The best way is to check your motherboard manual. If you can't find the manual, you can use a multimeter to measure it. Find the ground first, then you can determine the order of the rest of the wiring. How to connect motherboard VDG wiring When connecting the VDG wiring of the motherboard, you need to plug one end of the VGA cable into the VGA interface of the monitor and the other end into the VGA interface of the computer's graphics card. Please be careful not to plug it into the motherboard's VGA port. Once connected, you can

Automount drives on Linux Automount drives on Linux Mar 20, 2024 am 11:30 AM

If you are using a Linux operating system and want the system to automatically mount the drive on boot, you can do this by adding the device's unique identifier (UID) and mount point path to the fstab configuration file. fstab is a file system table file located in the /etc directory. It contains information about the file systems that need to be mounted when the system starts. By editing the fstab file, you can ensure that the required drives are loaded correctly every time the system starts, thus ensuring stable system operation. Automatically mounting drivers can be conveniently used in a variety of situations. For example, I plan to back up my system to an external storage device. To achieve automation, ensure that the device remains connected to the system, even at startup. Likewise, many applications will directly

Outlook freezes when inserting hyperlink Outlook freezes when inserting hyperlink Feb 19, 2024 pm 03:00 PM

If you encounter freezing issues when inserting hyperlinks into Outlook, it may be due to unstable network connections, old Outlook versions, interference from antivirus software, or add-in conflicts. These factors may cause Outlook to fail to handle hyperlink operations properly. Fix Outlook freezes when inserting hyperlinks Use the following fixes to fix Outlook freezes when inserting hyperlinks: Check installed add-ins Update Outlook Temporarily disable your antivirus software and then try creating a new user profile Fix Office apps Program Uninstall and reinstall Office Let’s get started. 1] Check the installed add-ins. It may be that an add-in installed in Outlook is causing the problem.

At a glance: A quick overview of how to open JSP files At a glance: A quick overview of how to open JSP files Jan 31, 2024 pm 09:28 PM

JSP file opening method JSP (JavaServerPages) is a dynamic web page technology that allows programmers to embed Java code in HTML pages. JSP files are text files that contain HTML code, XML tags, and Java code. When a JSP file is requested, it is compiled into a JavaServlet and then executed by the web server. Methods of Opening JSP Files There are several ways to open JSP files. The easiest way is to use a text editor,

Python ORM Performance Benchmark: Comparing Different ORM Frameworks Python ORM Performance Benchmark: Comparing Different ORM Frameworks Mar 18, 2024 am 09:10 AM

Object-relational mapping (ORM) frameworks play a vital role in python development, they simplify data access and management by building a bridge between object and relational databases. In order to evaluate the performance of different ORM frameworks, this article will benchmark against the following popular frameworks: sqlAlchemyPeeweeDjangoORMPonyORMTortoiseORM Test Method The benchmarking uses a SQLite database containing 1 million records. The test performed the following operations on the database: Insert: Insert 10,000 new records into the table Read: Read all records in the table Update: Update a single field for all records in the table Delete: Delete all records in the table Each operation

Application of Python ORM in big data projects Application of Python ORM in big data projects Mar 18, 2024 am 09:19 AM

Object-relational mapping (ORM) is a programming technology that allows developers to use object programming languages ​​to manipulate databases without writing SQL queries directly. ORM tools in python (such as SQLAlchemy, Peewee, and DjangoORM) simplify database interaction for big data projects. Advantages Code Simplicity: ORM eliminates the need to write lengthy SQL queries, which improves code simplicity and readability. Data abstraction: ORM provides an abstraction layer that isolates application code from database implementation details, improving flexibility. Performance optimization: ORMs often use caching and batch operations to optimize database queries, thereby improving performance. Portability: ORM allows developers to

See all articles