Home Development Tools composer Teach you to use Composer to manage dependencies

Teach you to use Composer to manage dependencies

Aug 07, 2020 pm 01:23 PM
composer

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
Copy after login

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

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

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
Copy after login

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
Copy after login

or simply change it to an executable file

>mv composer.phar composer
>chmod +x composer
Copy after login

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"
}
}
Copy after login

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$
Copy after login

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
Copy after login

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": [
....下略
Copy after login

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
...下略
Copy after login

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;
Copy after login

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
Copy after login

只要引用这个档案,就可以载入套件中所有对外公开的类别。基本上每个套件都会定义自己的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 of this Website
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

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 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:

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

How to view the version number of laravel? How to view the version number of laravel How to view the version number of laravel? How to view the version number of laravel Apr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

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

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

How to simplify email marketing with Composer: DUWA.io's application practices How to simplify email marketing with Composer: DUWA.io's application practices Apr 18, 2025 am 11:27 AM

I'm having a tricky problem when doing a mail marketing campaign: how to efficiently create and send mail in HTML format. The traditional approach is to write code manually and send emails using an SMTP server, but this is not only time consuming, but also error-prone. After trying multiple solutions, I discovered DUWA.io, a simple and easy-to-use RESTAPI that helps me create and send HTML mail quickly. To further simplify the development process, I decided to use Composer to install and manage DUWA.io's PHP library - captaindoe/duwa.

laravel installation code laravel installation code Apr 18, 2025 pm 12:30 PM

To install Laravel, follow these steps in sequence: Install Composer (for macOS/Linux and Windows) Install Laravel Installer Create a new project Start Service Access Application (URL: http://127.0.0.1:8000) Set up the database connection (if required)

See all articles