search
HomeDevelopment ToolscomposerHow to load Composer you don't know

How to load Composer you don't know

Sep 25, 2019 pm 03:54 PM
composer

我们都知道Composer是现代PHP框架(Yii2、Laravel...)的基石,有了Composer后我们开发是一件多么的爽的事情。那么Composer加载方式你知道多少呢?下面由composer使用教程栏目给大家介绍你不知道的composer加载方式。

How to load Composer you don't know

本文仅仅关注Composer的自动加载。

我们以Yii2为例,当我们通过Composer生成了一个Yii2程序后,会在vendor下建立一个autoload.php文件,它负责帮我们自动加载vendor内的各种库(yii2核心库也在vendor内,你懂得!)。

而你一定知道Yii2的入口文件index.php有一行。

require(__DIR__ . '/../vendor/autoload.php');

由此可见,Yii2对Composer的友好程度,也难怪~孤木不成林,Yii2也要靠无数个Composer扩展枝干才能变成参天大树。

下面开始正式讲解Composer的autoload,告诉你各式各样扩展安装后,我们并没有使用include / require,那么Composer是如何帮我们找到他们的那?

目前为止,Composer一共支持4种自动加载方式

PSR-0
PSR-4
class-map
直接包含file

这四种方式足以让Composer涵盖地球上所有的PHP第三方扩展库。

PSR是一套PHP开发标准,现在大多数主流框架都在支持,工兵连已经开专题分享PSR干货。

PSR-4

PSR-4是Composer推荐使用的一种方式,因为它更易使用并能带来更简洁的目录结构。在一个扩展的composer.json里是这样进行配置的:

{
    "autoload": {
        "psr-4": {
            "Foo\\": "src/",
        }
    }
}

key和value就定义出了namespace以及其对应的目录映射。按照PSR-4的规则,当试图自动加载"Foo\Bar\Baz"类的使用,会去寻找"srcBarBaz.php"这个文件,如果它存在则加载,要注意的是此时"Foo\"并不会出现在文件路径中。

而composer.json这样的配置会被Composer转换成namespace与文件目录的MAP形式,并存在vendor/composer/autoload_psr4.php文件中,所以如果你安装的某个扩展自动加载是PSR-4形式,你可以在autoload_psr4.php找到它的真实路径。

PSR-0

这是一个已经过时的标准,那是在遥远的PHP5.2时代,你我都知道,PHP5.3之后才有了类似namespace这样的高级属性,所以PSR-0更多是考虑

有点蒙圈么?那我们来看代码你就明白了。

{
    "autoload": {
        "psr-0": {
            "Foo\\": "src/",
        }
    }
}

我们来分析这个扩展的加载方式,什么是伪namespace那?当我们用这个库的时候

$model = new Foo_Bar_Baz();

对的,PSR-0的时代,有很多以下划线分隔的类名,它代表。。。它代表。。。

src/Foo/Bar/Baz.php

聪明的你一定明白什么是伪namespace了吧,通过命名的下划线来映射目录结构。

哎,那个时代的标准制定者们也真心不容易呀。

Class-map方式

{
    "autoload": {
        "classmap": ["src/", "lib/"]
    }
  }

这个加载方式比较容易理解,当Composer开始安装扩展的时候,会根据composer.json里的这个 autoload 告诉的方式classmap,来遍历src、lib目录然后将里面的类文件和其路径一一对应,存放到vendor/composer/autoload_classmap.php内。

例如src/下有一个BaseController类,那么在autoload_classmap.php文件中,就会生成这样的配置:

'BaseController' => $baseDir . '/src/BaseController.php'

若你还不懂,去看看autoload_classmap.php吧。

File方式

有了上面这些加载方式还不够么? 是的,还会有一些供全局使用的比如帮助等这样函数,那么好吧,我们就讲这些文件直接包含进来好了。

{
    "autoload": {
        "files": ["src/MyLibrary/functions.php"]
    }
}

Composer安装扩展后会将其放到

vendor/composer/autoload_files.php

到此刻,世界清静了,Composer可以加载我大PHP世界的各种库,只要你想,就可以自动加载。

The above is the detailed content of How to load Composer you don't know. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Composer: An Introduction to the PHP Dependency ManagerComposer: An Introduction to the PHP Dependency ManagerApr 21, 2025 am 12:02 AM

Composer is a dependency management tool for PHP, which is used to manage libraries and packages required by projects. 1) It defines dependencies through composer.json file, 2) installs and updates using command line tools, 3) automates the dependency management process, improves development efficiency, 4) supports advanced functions such as dynamically adding dependencies and automatic loading, 5) Ensures consistency of the team environment through composer.lock file.

The Purpose of Composer: Managing Dependencies EfficientlyThe Purpose of Composer: Managing Dependencies EfficientlyApr 20, 2025 am 12:04 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json and composer.lock files. 1. Create the composer.json file and run the composerinstall installation dependency. 2. Use composerrequire to add new dependencies. 3. Configure autoload to implement automatic loading of classes. 4. Use composerdiagnose to check the health status of the project. 5. Optimize dependency management: specify the package name update, use composerdump-autoload-o to optimize the autoloader, use composerinstall--no-d in the production environment

Composer and AI: New Possibilities in PHP DevelopmentComposer and AI: New Possibilities in PHP DevelopmentApr 19, 2025 am 12:03 AM

The combination of AI and Composer can improve PHP development efficiency and security. Specifically reflected in: 1. Dependency analysis and optimization: AI can predict dependencies and reduce conflicts. 2. Automated security checks: AI can identify security vulnerabilities, and it is recommended to update them. 3. Code generation and optimization: AI can automatically generate and optimize related code.

Using Dicr/Yii2-Google to integrate Google API in YII2Using Dicr/Yii2-Google to integrate Google API in YII2Apr 18, 2025 am 11:54 AM

VprocesserazrabotkiveB-enclosed, Мнепришлостольностьсясзадачейтерациигооглапидляпапакробоглесхетсigootrive. LEAVALLYSUMBALLANCEFRIABLANCEFAUMDOPTOMATIFICATION, ČtookazaLovnetakProsto, Kakaožidal.Posenesko

How to use Composer to resolve JSON Schema verification issuesHow to use Composer to resolve JSON Schema verification issuesApr 18, 2025 am 11:51 AM

I'm having a tricky problem when developing a Symfony-based application: how to effectively validate JSON data format. Initially, I tried using manual verification code, but this was not only complicated, but also error-prone. After some exploration, I discovered a Composer package called ptyhard/json-schema-bundle, which brought great convenience and efficiency to my project.

Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundleUse Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundleApr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

How to quickly build Fecmall advanced project templates using ComposerHow to quickly build Fecmall advanced project templates using ComposerApr 18, 2025 am 11:45 AM

When developing an e-commerce platform, it is crucial to choose the right framework and tools. Recently, when I was trying to build a feature-rich e-commerce website, I encountered a difficult problem: how to quickly build a scalable and fully functional e-commerce platform. I tried multiple solutions and ended up choosing Fecmall's advanced project template (fecmall/fbbcbase-app-advanced). By using Composer, this process becomes very simple and efficient. Composer can be learned through the following address: Learning address

Improve Doctrine entity serialization efficiency: application of sidus/doctrine-serializer-bundleImprove Doctrine entity serialization efficiency: application of sidus/doctrine-serializer-bundleApr 18, 2025 am 11:42 AM

I had a tough problem when working on a project with a large number of Doctrine entities: Every time the entity is serialized and deserialized, the performance becomes very inefficient, resulting in a significant increase in system response time. I've tried multiple optimization methods, but it doesn't work well. Fortunately, by using sidus/doctrine-serializer-bundle, I successfully solved this problem, significantly improving the performance of the project.

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

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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