search
HomeDevelopment ToolscomposerTeach you to use Composer to manage dependencies

The following tutorial column of composer will introduce you to using Composer to manage dependencies. I hope it will be helpful to friends in need!

Teach you to use Composer to manage dependencies

composer was originally a tool designed to manage package dependencies in Symfony, the PHP Framework. Because it is simple and easy to use, it has now become an independent open source project . Many frameworks and libraries can now be installed and managed using composer.

In fact, in PHP, there has been such a package dependency management tool for a long time, which is PEAR. However, the settings of PEAR are too complicated, and it is difficult to set dependencies for individual projects, so now Composer is loved by the public.

This introduction is only for users, so it will not cover the parts that package developers need to know.

* Installation

If you are a Windows user, you only need to download the installation file and execute the installation:

https://getcomposer.org/Composer-Setup.exe

If you want to install manually, you can refer to Guidelines from the official website:

http://getcomposer.org/doc/00-intro.md#installation-windows

If you are a user of UNIX Like system, you can install it through this command: (curl needs to be installed first)

curl -sS https://getcomposer.org/installer | php

The installation program will check the PHP settings. , and then download composer.phar to the current directory. To execute composer, you can execute

php composer.phar

or simply change it to an executable file

>mv composer.phar composer
>chmod +x composer

and then execute ./composer.

However, if you need them in different working directories and there is no problem with execution permissions, you can also copy the files directly to /usr/local/bin.

* Set dependencies

When using composer in a project, you must first generate a composer.json file, which specifies the package and version to be used. For example, when you need to use phpmailer to send a letter, you can specify it like this:

{
"require": {
"phpmailer/phpmailer": "~5.2.7"
}
}

and then execute the installation:

eng-Hsu-Pingteki-MacBook-Air:2-1a fillano$ composer install
Loading composer repositories with package information
Installing dependencies (including require-dev)
  - Installing phpmailer/phpmailer (v5.2.7)
    Downloading: 100%         
Writing lock file
Generating autoload files
Feng-Hsu-Pingteki-MacBook-Air:2-1a fillano$

and the installation is complete. Take a look at what is installed:

Feng-Hsu-Pingteki-MacBook-Air:2-1a fillano$ ls -l
total 16
-rw-r--r--  1 fillano  staff    66 10 11 18:15 composer.json
-rw-r--r--  1 fillano  staff  2330 10 11 18:16 composer.lock
drwxr-xr-x  5 fillano  staff   170 10 11 18:16 vendor

According to the files in the directory, we can find that originally there was only the composer.json file. After installation, there is a composer.lock file and the vendor directory. Let’s take a look at the contents of composer.lock first:

Feng-Hsu-Pingteki-MacBook-Air:2-1a fillano$ cat composer.lock
{
    "_readme": [
        "This file locks the dependencies of your project to a known state",
        "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file"
    ],
    "hash": "065c23f92d5ae579cb91beff67f41196",
    "packages": [
        {
            "name": "phpmailer/phpmailer",
            "version": "v5.2.7",
            "source": {
                "type": "git",
                "url": "https://github.com/PHPMailer/PHPMailer.git",
                "reference": "8717a79565b2c0ed67f851d70e1949febdf3b226"
            },
            "dist": {
                "type": "zip",
                "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/8717a79565b2c0ed67f851d70e1949febdf3b226",
                "reference": "8717a79565b2c0ed67f851d70e1949febdf3b226",
                "shasum": ""
            },
            "require": {
                "php": ">=5.0.0"
            },
            "require-dev": {
                "phpdocumentor/phpdocumentor": "*",
                "phpunit/phpunit": "*"
            },
            "type": "library",
            "autoload": {
                "classmap": [
                    "class.phpmailer.php",
                    "class.pop3.php",
                    "class.smtp.php"
                ]
            },
            "notification-url": "https://packagist.org/downloads/",
            "license": [
                "LGPL-2.1"
            ],
            "authors": [
....下略

looks like the information about the package that was just installed.

Let’s take a look at what’s in the vendor directory:

Feng-Hsu-Pingteki-MacBook-Air:2-1a fillano$ tree vendor
vendor
├── autoload.php
├── composer
│   ├── ClassLoader.php
│   ├── autoload_classmap.php
│   ├── autoload_namespaces.php
│   ├── autoload_real.php
│   └── installed.json
└── phpmailer
    └── phpmailer
        ├── LICENSE
        ├── PHPMailerAutoload.php
        ├── README.md
        ├── changelog.md
        ├── class.phpmailer.php
        ├── class.pop3.php
        ├── class.smtp.php
        ├── composer.json
        ├── docs
        │   ├── Callback_function_notes.txt
        │   ├── DomainKeys_notes.txt
        │   ├── Note_for_SMTP_debugging.txt
        │   ├── extending.html
        │   ├── faq.html
        │   ├── generatedocs.sh
        │   └── pop3_article.txt
...下略

It seems that in addition to the phpmailer directory where phpmailer is installed, there are mainly autoload.php files and composer directories.

It turns out that to load a package installed through composer, you need to reference the vendor/autoload.php file first, and then you can use phpmailer. Write a simple program to test it:

<?php
require &#39;vendor/autoload.php&#39;;
$phpmailer = new PHPMailer;

There are no errors after execution, which means phpmailer can load normally... Next, let’s take a look at the uses of these files.

* composer.json

For users, this file is mainly used to maintain dependencies. Just add an object to the file in the "require" attribute, where the attribute name is the package name and the value is the version. The package name is divided into two parts. The first part is the vendor, and the second part is the actual package name, separated by "\". There are several rules for versions:

  • Directly specify the version number, for example, 2.7.3

  • After specifying the main version number, use "*" to specify Minor version number, for example, 2.7.* means the version number is greater than or equal to 2.7.0. Versions less than 2.8.0

  • ## use >, >=, !=,
  • Use "~" before the version number , indicating the version before the next version number change. For example, ~2.7 means that the version is greater than or equal to 2.7 and less than 3.0

  • After the version number, you can also add different stability flags, such as 2.7.*@beta. The flags that can be used are: dev, alpha, beta, RC, stable

After specifying the version, execute composer install, and the latest version of the package will be installed according to the specified version rules.

In fact, every directory with a composer.json file is also the root directory of a package. However, if you want to make it a kit for others to use, you still need to add many settings, which are beyond the scope of this discussion.

* composer.lock

After the first installation of the package, this file will be generated, which records the information of the installed package. The real function of this file is: if there is this file in the directory, when performing the installation, it will not search for an updated version, but will install it according to the version recorded in this file. This design is important because the new version of the suite is likely to be incompatible with the currently used version. If the same version is not used, it is difficult to ensure the stability of the system. In the past, when using pear to manage packages, if you were not careful, tragedies caused by upgrades might occur.

In addition, as long as this file is added to version management, all developer directories will also have this file, so the package versions used by everyone will be consistent, which can reduce the need to use the package during development. Program compatibility issues caused by different versions.

* vendor directory

所有套件都会放置在这个目录,并且依照/的目录结构来组织。

* vendor/autoload.php

只要引用这个档案,就可以载入套件中所有对外公开的类别。基本上每个套件都会定义自己的autoload规则,在安装时,composer会把这些规则加入,这样透过autoload.php就可以直接使用所有已安装的类别。

=====

从这些地方可以看到,Composer这个套件管理工具,在设计上已经做了很周密的考量,只需要简单指定要使用的套件及版本,一个指令就可以安装完毕,引用一个胆案之后就能使用,这样真的非常方便。所以目前几乎所有的程式库以及Framework,应该都逐渐在套用这个工具了。未来在开发PHP程式,恐怕最基本的工具也就是composer。

The above is the detailed content of Teach you to use Composer to manage dependencies. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:ithome. If there is any infringement, please contact admin@php.cn delete
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.

Identifying a Composer: The Essential ElementsIdentifying a Composer: The Essential ElementsApr 27, 2025 am 12:27 AM

The key steps to identifying a composer include: 1) analyzing the composer's stylistic characteristics, such as Beethoven's drama and power; 2) understanding the composer's historical background and cultural influence, such as Bach's Baroque style; 3) comprehensively analyzing the melody, harmony, rhythm and structure of the work to avoid misjudgment caused by relying solely on a single element.

Composer: The Future of AI in PHP DevelopmentComposer: The Future of AI in PHP DevelopmentApr 26, 2025 am 12:10 AM

Composer'sfutureinPHPdevelopmentwithAIincludes:1)AI-enhanceddependencymanagementforsuggestinglibraries,2)AI-drivencodegenerationfortailoredboilerplate,and3)predictivemaintenanceforupdatesandpatches,butfaceschallengeslikedataprivacyandAIbias.

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development 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.

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!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.