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
What is a composer doing?What is a composer doing?Apr 08, 2025 am 12:19 AM

Composer is a dependency management tool for PHP, used to declare, download and manage project dependencies. 1) Declare dependencies through composer.json file, 2) Install dependencies using composerinstall command, 3) parse the dependency tree and download it from Packagist, 4) generate the autoload.php file to simplify automatic loading, 5) optimize use includes using composerupdate--prefer-dist and adjusting the autoload configuration.

What is App composer?What is App composer?Apr 07, 2025 am 12:07 AM

AppComposer is a tool for building and managing applications. 1) It simplifies application development and improves efficiency by dragging and configuring predefined components. 2) Developers can define components, combine interfaces, define business logic, and ultimately render the application. 3) Support basic and advanced usage, such as task management and conditional rendering, helping to build flexible applications.

What is a composer used for?What is a composer used for?Apr 06, 2025 am 12:02 AM

Composer is a dependency management tool for PHP. The core steps of using Composer include: 1) Declare dependencies in composer.json, such as "stripe/stripe-php":"^7.0"; 2) Run composerinstall to download and configure dependencies; 3) Manage versions and autoloads through composer.lock and autoload.php. Composer simplifies dependency management and improves project efficiency and maintainability.

What is Composer AI?What is Composer AI?Apr 05, 2025 am 12:13 AM

ComposerAI is an artificial intelligence-based tool for generating and optimizing code to improve development efficiency and quality. Its functions include: 1. Code generation: generate code snippets that meet the standards according to requirements. 2. Code optimization: By analyzing existing code, make optimization suggestions. 3. Automated testing: Generate test cases to ensure code quality.

What is composer in Android?What is composer in Android?Apr 04, 2025 am 12:18 AM

Composer is part of the SurfaceFlinger service in Android, and is responsible for synthesising multiple graphics layers into the final display buffer. 1) Collect the graphics layer, 2) sort the graphics layer, 3) synthesize the graphics layer, 4) output to the display device to improve application performance and user experience.

What is the definition of a composer?What is the definition of a composer?Apr 03, 2025 am 12:17 AM

Composers are people who make music, express emotions, tell stories, and convey ideas through music. The composer's work includes: 1. Concept: determine the theme and style of the work; 2. Creation: compose melody and harmony to form a preliminary musical structure; 3. Experiment: audition and adjustment of the work through instruments or software; 4. Improvement: modify and improve according to the audition results until you are satisfied.

What is the difference between composer and orchestrator?What is the difference between composer and orchestrator?Apr 02, 2025 pm 02:49 PM

Composer is used to manage dependencies on PHP projects, while Orchestrator is used to manage and coordinate microservices or containerized applications. 1.Composer declares and manages dependencies of PHP projects through composer.json file. 2. Orchestrator manages the deployment and extension of services through configuration files (such as Kubernetes' YAML files), ensuring high availability and load balancing.

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

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use