search
HomeBackend DevelopmentPHP TutorialPHP namespace autoloading: How to use composer's autoload to achieve automatic loading

在 PHP5 以后的版本中可以定义一个 __autoload() 函数,当调用一个未定义的类的时候就会启动此函数,从而在抛出错误之前做最后的补救,不过这个函数的本意已经被完全曲解使用了,现在都用来做自动加载。后来这个函数实际上已经不被推荐使用了,相反,现在应当使用 spl_autoload_register() 来注册类的自动加载函数。前面我们介绍了php命名空间的基本知识,使用方法,作用等等,这一节就重点来说说php命名空间自动加载。

spl_autoload_register() 的语法格式如下:

bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )

autoload_function 是需要注册的自动装载函数,如果此项为空,则会注册 spl_autoload 函数,

throw 此参数设置了 autoload_function 无法成功注册时, spl_autoload_register() 是否抛出异常。

prepend 如果是 true, spl_autoload_register() 会添加函数到队列之首,而不是队列尾部。

上面提到了 spl_autoload 函数,实际上注册函数的规范就应当遵循此函数,函数声明如下:

void spl_autoload ( string $class_name [, string $file_extensions ] )

由于这个函数默认实现是通过 C 语言,所以这里给出一个 PHP 语言的实现规范。

其实例代码如下:

<?php
// 自定义类
define(&#39;CLASS_DIR&#39;, &#39;class/&#39;);
// 添加类的路径
set_include_path(get_include_path().PATH_SEPARATOR.CLASS_DIR);
// 使用自动加载添加类
spl_autoload_extensions(&#39;.class.php&#39;);
// 默认加载
spl_autoload_register();
?>

大致上就和这个是类似的。实际上命名空间和自动加载类的结合就基本是通过路径形式。

使用composer的autoload来自动加载

composer的出现真是让人们眼前一亮,web开发从此变成了一件很“好玩”的事情,开发一个CMS就像在搭积木,从packagist中取出“ 积木 ”搭建在自己的代码中,一点一点搭建出一个属于自己的王国。

使用composer基本就可以抛弃了require和include函数,一个项目中,这两个函数只可能出现一次,那就是 require '../vendor/autoload.php'。

然后就可以非常方便的去使用第三方的类库了,是不是感觉很棒啊!对于我们需要的monolog,就可以这样用了:

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// 创建日志
$log = new Logger(&#39;name&#39;);
$log->pushHandler(new StreamHandler(&#39;/path/to/log/log_name.log&#39;, Logger::WARNING));
// 将记录添加到日志
$log->addWarning(&#39;Foo&#39;);
$log->addError(&#39;Bar&#39;);

在这个过程中,Composer做了什么呢?它生成了一个autoloader,再根据各个包自己的autoload配置,从而帮我们进行自动加载的工作。

实现方式的步骤:

1. 先安装composer,可以参照php依赖管理工具composer入门教程

2. 在项目根目录创建composer.json文件,写入代码

{
    "type": "project",
    "autoload": {
        "psr-4": {
            "Admin\\": "admin/"
        }
    }
}

3. 在项目根目录打开命令,写入命令

composer update

4.等待执行完成。安装成功后,会在项目根目录下新建一个"/vendor/"文件夹。

说明:使用之前需要require一下"/vendor/autoload.php"文件。

$autoLoadFilePath = dirname($_SERVER[&#39;DOCUMENT_ROOT&#39;]).DIRECTORY_SEPARATOR.&#39;vendor&#39;.DIRECTORY_SEPARATOR.&#39;autoload.php&#39;;
require_once $autoLoadFilePath;

5. 在"/admin/"目录下新建test.php文件,文件内容如下

<?php
namespace Admin;
class test
{
   public function sayHi()
   {
       echo &#39;hi&#39;;
   }
}
?>

 在"/public/"目录下新建index.php文件,文件内容如下

sayHi();
?>

6. 配置apache,访问路径,得到如下的结果就表示成功。

PHP namespace autoloading: How to use composers autoload to achieve automatic loading

【相关教程推荐】

1. 《php.cn独孤九贱(4)-php视频教程

2.  视频教程:命名空间:我们虽然同名同性,但却属于不同时空

3.  php编程从入门到精通全套教程

The above is the detailed content of PHP namespace autoloading: How to use composer's autoload to achieve automatic loading. For more information, please follow other related articles on the PHP Chinese website!

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 Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools