Table of Contents
什么是Composer
Composer的安装
本地安装
全局安装
安装选项
--install-dir
--filename
--version
手动下载
Composer的更新
Composer的基本使用
composer.json文件
require键
包的名称
包的版本
安装依赖
composer.lock文件
更新依赖
自动加载
Packagist 镜像
参考
Home Backend Development PHP Tutorial Composer快速入门

Composer快速入门

Jun 20, 2016 pm 12:26 PM

什么是Composer

Composer是PHP的一个依赖管理工具。你可以在你的项目里声明你依赖的库,然后Composer会帮你解决以下问题:找到这些库以及这些库所依赖的库可以安装的版本,然后进行安装。所以Composer是一个依赖管理工具,而不是一个包管理工具(类似Yum或者Apt),因为它是基于每个项目去管理这些包,把这些包安装到项目里的某个目录。

Composer的安装

Composer要求 PHP 5.3.2+版本以及一些PHP的配置,如果有不兼容的情况发生,在安装过程中会有提示。有两种方式安装Composer,一是本地安装,而是全局安装。

本地安装

本地安装会把Composer安装到当前的目录下。运行以下命令进行安装:

$ php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"$ php -r "if (hash_file('SHA384', 'composer-setup.php') === '070854512ef404f16bac87071a6db9fd9721da1684cd4589b1196c3faf71b9a2682e2311b36a5079825e155ac7ce150d') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"$ php composer-setup.php$ php -r "unlink('composer-setup.php');"
Copy after login

一共4条命令,它们分别执行以下的操作:

  1. 下载安装文件到当前目录。

  2. 检验安装文件的SHA-384散列。

  3. 运行安装文件。

  4. 删除安装文件。

然后我们就可以运行执行以下命令来运行Compoer了:

$ php composer.phar
Copy after login

需要注意的是,第二步检查文件的散列,每一个版本安装文件的散列值都会不同的,所以每次安装最好都到 下载页面去获取安装代码。或者如果你觉得没有检查安装文件的必要的话,也可以跳过这条命令去执行下面的命令。当然从安全角度考虑,不建议这么做。

全局安装

所谓全局安装,其实就是把Composer安装到 PATH变量里的某个目录中,这样你就可以从任何地方去访问Composer了。个人也建议这么做。我们只需要把本地安装的composer执行文件移动到全局目录下即可:

$ mv composer.phar /usr/local/bin/composer
Copy after login

这样你就可以在任何地方直接运行 composer命令了。后续如没有特别说明,都是在全局安装的情况下执行命令。

安装选项

Composer安装时支持3个选项。

--install-dir

通过 --install-dir选项可以修改Composer的安装路径,例如如果我们想把Composer安装在 bin目录下:

$ php composer-setup.php --install-dir=bin
Copy after login

--filename

通过 --filename选项,我们可以修改Composer执行文件的名称(默认为composer.phar)。例如:

$ php composer-setup.php --filename=composer
Copy after login

--version

如果想安装指定版本的Composer,可以使用 --version选项:

$ php composer-setup.php --version=1.0.0-alpha8
Copy after login

手动下载

除了上面的安装方式外,还可以直接下载执行文件,请到 下载页面进行下载。

Composer的更新

更新Composer很简单,只需要执行以下命令:

$ composer selfupdateUpdating to version 1.1.2 (stable channel).    Downloading: 100%         Use composer self-update --rollback to return to version 06c45623d76457562cecbcf2245f904aa0f63a87# 或者(两者是等效的)$ composer self-update
Copy after login

如果想进行版本的回滚,可以使用以下命令:

$ composer selfupdate --rollbackRolling back to version 2016-05-26_16-11-16-06c4562.
Copy after login

Composer的基本使用

composer.json文件

安装完Composer后,想要在项目里开始使用它,你唯一需要做的就是创建一个 composer.json文件。这个文件描述了你这个项目所依赖的包以及一些其他的元信息。

require键

通过require这个配置项,我们可以指定项目的依赖。假设我们项目需要用到 monolog/monolog这个日志库,那么我们可以这样配置 composer.json文件:

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

require的值是一个对象,对象里的每一个键对应一个依赖,通过键名为包的名称,键值为包的版本。

包的名称

包名由vendor名和项目名组成,这样可以保证包名的唯一性。项目名可以重复,但是vendor名每个人都不一样。以 monolog/monolog为例,vendor名和项目名都是 monolog。

包的版本

在上面的例子中,我们要求 monolog/monolog的版本为 1.0.*,表示任何的1.0的开发分支版本都满足要求。版本的指定方式有很多种,在后面的文章中会进行详细的解说。

安装依赖

创建完 composer.json文件并配置好 require后,我们就可以安装依赖了,只需要运行以下的命令:

$ composer installLoading composer repositories with package informationUpdating dependencies (including require-dev)  - Installing monolog/monolog (1.0.2)    Downloading: 100%         Writing lock fileGenerating autoload files
Copy after login

Composer会根据上面配置的版本约定下载最新版本的 monolog/monolog到默认目录 vendor下。

composer.lock文件

运行完上面的 install命令后,你会发现除了 vendor目录,还会多了一个 composer.lock文件。这个文件保存了项目已经安装的每个包的具体版本。在运行 install命令的时候,如果存在这个文件,则Composer会根据这个文件下载对应版本的包。这样的好处是可以保证各个环境的依赖的版本一致,否则如果没有这个文件,每个环境在运行 install时可能下载到的版本就不一致了。所以建议把 composer.lock文件也放到版本控制里。

更新依赖

要更新依赖,只需要运行 update命令:

# 更新所有的依赖$ composer update# 更新某个依赖$ composer update monolog/monolog
Copy after login

自动加载

下载完依赖后,我们可以开始使用依赖所提供的库了。Composer会为下载的库创建自动加载文件 vendor/autoload.php,我们只需要包含这个文件就能轻松的调用各个库的功能。以 monolog/monolog为例:

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

我们不用关心库文件的加载问题,Composer的 autoload.php文件已经帮我们处理好了各个库的自动加载。

Packagist 镜像

至此,我们安装好了Composer,也知道了它的基本用法,基本可以快乐的玩耍了。但是众所周知,由于某些原因,github和packagist在国内有时会访问不了,或者速度很慢,这就会导致使用Composer时的各种不爽。还好我们国内有个 镜像可以解决这个问题,只需要把仓库的路径修改为镜像的路径即可。

有两种方式,一是修改Composer的全局配置(推荐的方式):

$ composer config -g repo.packagist composer https://packagist.phpcomposer.com
Copy after login

这个命令会修改Composer的全局配置文件 config.json。二是修改单个项目的配置:

$ composer config repo.packagist composer https://packagist.phpcomposer.com
Copy after login

这个命令会修改项目下的 composer.json文件,添加如下的配置信息:

"repositories": {    "packagist": {        "type": "composer",        "url": "https://packagist.phpcomposer.com"    }}
Copy after login

当然你也可以直接手动修改 composer.json文件,添加上面那段配置信息。

详情请访问: http://pkg.phpcomposer.com/。

参考

  • https://getcomposer.org/

  • http://pkg.phpcomposer.com/

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles