Home Development Tools composer Composer usage tutorial (basic usage)

Composer usage tutorial (basic usage)

Aug 29, 2019 pm 02:29 PM
composer

Composer is a dependency management tool for PHP. With it, we can easily use one command to reference other excellent codes into our projects. Below, the composer usage tutorial column will explain the basic usage of Composer. I hope it will be helpful to friends in need!

Composer usage tutorial (basic usage)

Basic usage

Introduction

Introducing basic usage, we will install monolog /monolog logging library as an example. Such as

Note: For simplicity, we assume that you have Composer installed locally.

composer.json: Project Settings

To use Composer in your project you need a composer.json file. This file describes your project dependencies and other metadata.

require key

The first (and usually only) thing you should do is define the require key in your composer.json file. You should briefly tell Composer which packages your project depends on.

{
    "require": {
        "monolog/monolog": "1.0.*"
    }
}
Copy after login

As shown above, require obtains a json object with a package name (such as monolog/monolog) mapped to a version constraint (such as 1.0.*).

Composer uses this information to search for appropriate files in the version repository specified by the repositories key you registered in Composer.json, or the default package repository in Packagist. In the above example, because there is no other repository information registered in the composer.json file, it assumes that the monolog/monolog package is in Packagist by default. (See below for more Packagist information, or read more about it here.

Package Name

The package name consists of the vendor name and the project name. Typically In the case where these names are the same, the presence of the vendor name resolves naming conflicts. For example, it allows two different people to create a library with the same name Json. It can be named igorw/json and seldaek/json .

Here you can read more about publishing packages and package naming.

Note that you can also specify a "platform package" as a dependency, which allows you to customize some version of the server software. See Platform Software Packages below

Package Version Constraints

In the example above, the monolog version we introduced was specified as 1.0.*. This means that any development branch starting from 1.0, it will match versions greater than or equal to 1.0 and less than 1.1.

Please read for more in-depth information about versions, how they are related to each other or how to version control.

How does Composer download the correct file? When you specify a dependency in composer.json, Composer first gets the name of the package you requested and searches for it in any repositories that have been registered with the library key. If you haven't registered any additional repositories, or it doesn't find a package with that name in the repository you specified, it falls back to Packagist (details below).

When Composer is in the packager When the correct package is found in a repository for a specified package, it uses the versioning feature of the package's VCS (i.e. branches and tags) to try to find the best match for the version constraints you specified. Be sure to read about versions and package declaration articles.

Note: If you try to fetch a package and Composer throws an error about package stability, the version you specify may not meet the default minimum stability requirements. By default , stable versions will only be considered when searching for valid package versions in VCS.

If you also want to get DEV, Alpha, Beta or RC versions. Read more about stable flags and minimum-stability key on the schema page.

Install dependencies

Use the install command to install the defined dependencies for your project

php composer.phar install
Copy after login

Run this command , composer will be installed in one of the following two ways depending on the situation

Non-composer.lock installation

If you have never run the command before, it will not When the composer.lock file appears, Composer will only parse the dependencies you listed in the composer.json file and download the latest version to your project's vendor directory (vendor is the regular directory in the project where all third-party code is stored). In our example above, you would end up with all Monolog source files in the vendor/monolog/monolog/ directory. If Monolog has any dependencies, they will also appear in vendor/.

Tips:If you use git in your project, you may want to add vendor to .gitignore. Because adding all third-party packages to the repository seems silly.

When Composer completes the installation, it will write all downloaded packages and exact version information to the composer.lock file to lock the versions of third-party packages in the project. You should place composer.lock in the project repository so that all members of the project are locked to the same version of their dependencies

Install using the composer.lock file

这里来到了第二种安装方式。如果你在运行 composer install 命令之前已经存在了 composer.lock 和 composer.json 文件, 这意味着你之前使用了 install 命令, 或者项目中的其他成员使用了 install 命令并将 composer.lock 文件提交至了项目中 (这是非常好的)。

无论使用哪种方式,存在 composer.lock 文件时使用 install 命令安装依赖时 composer.lock 都会解析并安装你在 composer.json 中所列出来的依赖,但是 Composer 会严格使用 composer.lock 文件列出来的版本来确保项目中的所有成员所安装的版本都是一致的。因此,你可以获得 composer.json 文件列出的所有文件,但是与此同时他们可能并不是最新的可用版本 (一些在 composer.lock 文件中列出的依赖可能会在这个文件创建之后释放了新的版本)。这个是设计上的,这样的设计可以确保你的项目不会因为一些依赖的改变而崩溃。

提交你的 composer.lock 文件至版本控制工具

将此文件提交至 VC 是非常重要的。因为它可以确保项目中的任何人使用的都是与你是完全一致的依赖。 你的 CI 服务器,生产服务器,团队的其他开发人员,所有人都使用的是相同的依赖项,这减轻了仅部署某些部分而引起错误的可能性。即使你独立开发,在你重新安装项目的 6 个月内,你的依赖项发布了许多新的版本,你依然可以确信你的依赖项是可用的。(请参阅下边有关使用 update 的命令。)

更新依赖到最新版本

如上所述,composer.lock 文件将阻止你自动获取最新依赖版本。如果要更新依赖到最新版本,使用 update 命令。这将获取最新匹配的版本(根据你的 composer.json 文件)并将新版本更新到 composer.lock 文件。(这相当于删除 composer.lock 文件并再次运行 install)。

php composer.phar update
Copy after login

注意:当执行 install 命令时,由于 composer.json 的更改可能影响到依赖解析而未更新 composer.lock ,Composer 将显示警告。

如果只是想安装或更新一个依赖,可以将它们列出来:

php composer.phar update monolog/monolog [...]
Copy after login

注意:对于库来说,没必要提交 composer.lock 文件,请参考:库 - 锁文件。

Packagist

Packagist 是 Composer 的主要资源库。一个 Composer 库基本上是一个包的源:一个你可以得到包的地方。

Packagist 的目标是成为一个任何人都可以使用的中央仓库。这意味着你可以 require 那里的任何包,无需指定 Composer 查找包的位置。

当你访问 Packagist 网站 (packagist.org),你可以浏览和搜索包。

建议使用 Composer 的开源项目在 Packagist 上发布包。虽然并不一定需要发布在 Packagist 上来被 Composer 使用,但是它能被其它的开发者更快的发现和采用。

平台包

Composer 将那些已经安装在系统上,但并不是由 Composer 安装的包视为虚拟的平台包。这包括 PHP 本身、PHP 扩展和一些系统库。

php 代表使用的 PHP 版本要求,允许你应用限制,例如 ^7.1 。如果需要 64 位版本的 PHP, 你可以使用 php-64bit 进行限制。

hhvm 代表 HHVM 运行环境的版本,并且允许你应用限制 ,例如,^2.3。

ext- 允许你依赖 PHP 扩展(包括核心扩展)。通常 PHP 拓展的版本可以是不一致的,将它们的版本约束为 * 是一个不错的主意。一个 PHP 扩展包的例子是:ext-gd。

lib- 允许对 PHP 库的版本进行限制。以下可用例子: curl, iconv, icu,libxml,openssl, pcre, uuid, xsl。

你可以使用命令 show --platform 去获取你本地可用的平台包。

自动加载

为了描述包的自动加载信息, Composer 会生成一个 vendor/autoload.php 文件,你可以简单的 include 这个文件,并在无需其它额外工作的情况下就可以使用这些包所提供的类:

require __DIR__ . '/vendor/autoload.php';
$log = new Monolog\Logger('name');
$log->pushHandler(new Monolog\Handler\StreamHandler('app.log', Monolog\Logger::WARNING));
$log->addWarning('Foo');
Copy after login

你甚至可以在 composer.json 中添加一个 autoload 指令,来添加自己的自动加载声明

{
    "autoload": {
        "psr-4": {"Acme\\": "src/"}
    }
}
Copy after login

Composer 会为 Acme 命名空间注册一个 PSR-4 的自动加载.

你定义一个命名空间指向目录的映射。 在 vendor 目录同级的 src 目录将成为你项目的根目录。一个案例,文件名 src/Foo.php 需包含 AcmeFoo 类。

添加 autoload 指令之后,你必需重新运行 dump-autoload 来重新生成 vendor/autoload.php 文件。

包含此文件后也可以接收到一个 autoloader 实例,由因此您可以将 include 调用的返回值存储在变量中并添加更多名称空间,这在测试套件中将会很有用,例如:

$loader = require DIR . '/vendor/autoload.php';
$loader->addPsr4('Acme\Test\', __DIR__);
Copy after login

作为 PSR-4 自动加载规范的补充,Composer 也支持 PSR-0、类表、文件清单的自动加载方式。具体请查询 autoload 引用。

你也可以查阅 optimizing the autoloader 了解关于自动加载器的优化.

注意:

Composer 提供自己的加载器,但如果你不想使用那个而想自己配置加载器的话,你可以试试 include vendor/composer/autoload_*.php 这些文件所返回的关联数组来实现。

The above is the detailed content of Composer usage tutorial (basic usage). 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)

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.

Use Composer to solve dependency injection: application of PSR-11 container interface Use Composer to solve dependency injection: application of PSR-11 container interface Apr 18, 2025 am 07:39 AM

I encountered a common but tricky problem when developing a large PHP project: how to effectively manage and inject dependencies. Initially, I tried using global variables and manual injection, but this not only increased the complexity of the code, it also easily led to errors. Finally, I successfully solved this problem by using the PSR-11 container interface and with the power of Composer.

How to quickly build LaravelCMS with Composer: mki-labs/espresso practical experience How to quickly build LaravelCMS with Composer: mki-labs/espresso practical experience Apr 18, 2025 am 07:36 AM

I encountered a tricky problem when developing a new Laravel project: how to quickly build a fully functional and easy-to-manage content management system (CMS). I tried multiple solutions, but all gave up because of complex configuration and inconvenient maintenance. Until I discovered the LaravelCMS package mki-labs/espresso, which not only simple to install, but also provides powerful functions and intuitive management interface, which completely solved my problem.

How to resolve HTTP request issues using Composer: A practical guide to the yiche/http library How to resolve HTTP request issues using Composer: A practical guide to the yiche/http library Apr 18, 2025 am 08:06 AM

During development, HTTP requests are often required, which may be to get data, send data, or interact with external APIs. However, when faced with complex network environments and changing request requirements, how to efficiently handle HTTP requests becomes a challenge. I have encountered a problem in a project: I need to send requests to different APIs frequently, and log the requests to facilitate subsequent debugging and analysis. After trying several methods, I discovered the yiche/http library. It not only simplifies the processing of HTTP requests, but also provides dynamic logging functions, greatly improving development efficiency.

How to solve the problem of JavaScript error handling using Composer How to solve the problem of JavaScript error handling using Composer Apr 18, 2025 am 08:30 AM

I'm having a tough problem when developing a complex web application: how to effectively handle JavaScript errors and log them. I tried several methods, but none of them could meet my needs until I discovered the library dvasilenko/alterego_tools. I easily solved this problem through the installation of this library through Composer and greatly improved the maintainability and stability of the project. Composer can be learned through the following address: Learning address

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.

Practical experience in creating efficient command line interfaces using the Symfony/Console library Practical experience in creating efficient command line interfaces using the Symfony/Console library Apr 18, 2025 am 07:30 AM

In project development, it is often necessary to create command-line tools to simplify daily tasks or automate processes. However, creating a command line interface that is beautiful and easy to test is not easy. Recently, I encountered this problem while developing a project that requires command line tools. After some exploration, I found the Symfony/Console library, which greatly simplifies the creation process of command line interfaces.

How to use Composer to solve the problem of batch processing of data under Yii framework How to use Composer to solve the problem of batch processing of data under Yii framework Apr 18, 2025 am 07:54 AM

When developing Yii framework projects, you often encounter situations where you need to obtain a large amount of data from the database. If appropriate measures are not taken, directly obtaining all data may cause memory overflow and affect program performance. Recently, when I was dealing with a project on a large e-commerce platform, I encountered this problem. After some research and trial, I finally solved the problem through the extension library of pavle/yii-batch-result.

See all articles