search
HomeDevelopment ToolscomposerDetailed explanation of autoload in Composer series

下面由composer使用教程栏目为大家讲解Composer系列之autoload文件,希望对需要的朋友有所帮助!

Detailed explanation of autoload in Composer series

简介

Composer 是 PHP 的一个依赖管理工具。它允许你申明项目所依赖的代码库,它会在你的项目中为你安装他们。

对于类库的自动加载,Composer 生成了一个 vendor/autoload.php 文件。引入这个文件,就能得到一个免费的自动加载支持,这种感觉真是棒极了~

本文主要是介绍如何利用 Composer 自带的自动加载机制,加载本地自定义的包(即不是来自于 packagist)。

使用

在 composer.json 文件中的 autoload 字段中添加自己的 autoloader。

目前 Composer 支持四种自动加载映射的方式:

PSR-0 autoloading
PSR-4 autoloading
classmap generation
files

下面只介绍 PSR-4,为什么?因为它足够方便好用(当你添加类时不需要重新生成 autoloader)。详细请查看 自动加载 - 参考

PSR-4(推荐)

{
    "autoload": {
        "psr-4": {
            "First\\": "src/",
            "Temp\\": "lib/"
        }
    }
}

上面的代码采用 PSR-4 规范,该规范包含了 PHP 最新的自动加载标准,它要求必须使用 namespace (命名空间)的方式。

First\\ 表示命名空间,必须以 \\ 结尾,避免相似的命名空间导致冲突,若包含子命名空间,可以这样表示:First\\Second\\。

src/ 表示命名空间所在目录为与 Composer 的 vendor 目录同级的 src 目录,如下所示:

First/
|---examples/
    |---get.php
|---src/
    |---Curl.php
|---vendor/
    |---composer/
    |---autoload.php
|---composer.json

如果需要在多个目录下搜索相同的命名前缀,可以用一个数组提供:

{
    "autoload": {
        "psr-4": {"First\\": ["src/", "lib/"]}
    }
}

修改完 composer.json 的 autoload 字段后需要更新一下 Composer 的自动加载类:

composer dumpautoload -o

对应 Curl.php 的命名空间如下表示:

<?php
namespace First;
class Curl
{
}

引用 Curl.php 的方式如下:

<?php
require &#39;../vendor/autoload.php&#39;;
use First\Curl;
$curl = new Curl();
...
...

小结

之前一直以为 namespace 是 PHP 内置好的,只需要在某个类上声明一下某个命名空间,在调用这个类的地方 use 一下就好。。。

直到前几天脱离框架,单独写了几个类,然后被 xxx class not found 错误折磨到怀疑人生,才明白需要有个 autoloader 才行。

题外话

现在 Composer 已经成为 PHP 的依赖管理标杆,多利用这个工具为自己的开发带来方便。

框架能大大减少开发成本,但有时候不利于个人技术的提升。在使用热门框架时,多看看框架的代码,不仅帮助自己理解掌握框架,也能带来许多编程思想和技术上的提高。

The above is the detailed content of Detailed explanation of autoload in Composer series. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Composer: AI-Powered Tools and IntegrationsComposer: AI-Powered Tools and IntegrationsMay 05, 2025 am 12:11 AM

Composer itself does not include AI capabilities, but can be enhanced by AI tools. 1) AI can analyze composer.json files, and it is recommended to optimize dependencies and predict version conflicts. 2) AI-driven platforms such as GitHubCopilot can provide real-time code suggestions to improve development efficiency. When using AI tools, you need to verify and adjust them in combination with actual situations.

The Attributes of a Successful ComposerThe Attributes of a Successful ComposerMay 04, 2025 am 12:13 AM

The key traits of a successful composer include: 1) rich creativity and imagination, 2) solid mastery of technical skills and tools. These traits are similar to creative and structured thinking in programming, helping composers realize creativity and optimize their work in music creation.

The Requirements to Be a Composer: A Deep DiveThe Requirements to Be a Composer: A Deep DiveMay 03, 2025 am 12:08 AM

To become a composer, you need to master music theory, instrumental performance, be familiar with music style and history, and be creative and inspiring. Specific steps include: 1. Learn music theory, such as chord structure and rhythm mode; 2. Master the performance of musical instruments and improve creative inspiration; 3. Be familiar with music production software, such as AbletonLive, to improve creative efficiency; 4. Continuous practice and adjustment, create complex melodies and use discordant chords to increase music tension.

Composer: The Package Manager for PHP DevelopersComposer: The Package Manager for PHP DevelopersMay 02, 2025 am 12:23 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

The Integration of AI into Composer: Exploring PotentialThe Integration of AI into Composer: Exploring PotentialMay 01, 2025 am 12:02 AM

AI can show its strengths in the field of music creation. 1) AI generates music through machine learning and deep learning, enhancing diversity and innovation. 2) AI composers can assist composers and provide inspiration and creativity. 3) In actual applications, performance needs to be optimized to solve the problems of coherence and innovation in the generation of music.

Composer's Purpose: Managing Project Dependencies in PHPComposer's Purpose: Managing Project Dependencies in PHPApr 30, 2025 am 12:01 AM

We need Composer because it can effectively manage dependencies of PHP projects and avoid the hassle of version conflicts and manual library management. Composer declares dependencies through composer.json and uses composer.lock to ensure the version consistency, simplifying the dependency management process and improving project stability and development efficiency.

Composer: Aiding PHP Development Through AIComposer: Aiding PHP Development Through AIApr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

Becoming a Composer: Training, Education, and ExperienceBecoming a Composer: Training, Education, and ExperienceApr 28, 2025 am 12:11 AM

To become a composer, you need to master music theory, harmonization, counterpoint, and be familiar with the tone and performance skills of the instrument. Composers express emotions and stories through music, and the creative process involves the construction and improvement of ideas to works.

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)