PHP

Composer

Composer is a dependency management tool for PHP. It simplifies the process of managing libraries and packages in a PHP project by allowing developers to declare the libraries their project depends on, and it automatically handles installing and updating them.

Composer Installation

Windows

Open composer website and download the installer: Composer


Linux

Dependencies

$ sudo apt update
$ sudo apt install php-cli unzip

Installing Composer

$ cd ~
$ curl -sS https://getcomposer.org/installer -o /tmp/composer-setup.php
$ sudo php /tmp/composer-setup.php --install-dir=/usr/local/bin \
--filename=composer

Updating Composer

$ composer self-update

Configuration

$ composer config --global disable-tls true
$ composer config --global secure-http false

You can edit composer configuration by editing the ~/.composer/config.json on macOS or Linux.


Mirror

Change composer mirror globally:

$ composer config -g repos.packagist composer \
https://mirrors.tencent.com/composer/

Change composer mirror for a single project:

$ composer config repos.packagist composer \
https://mirrors.tencent.com/composer/

Other Mirrors:

  • Huawei: https://repo.huaweicloud.com/repository/php/
  • Aliyun: https://mirrors.aliyun.com/composer/

Create a Project

Composer Init

  1. Switch to the directory where you want to create the project.
  2. Run the following command to create a new Laravel project:
$ composer init

The wizard will ask you a series of questions to help you create a composer.json file for your project.

Package name (/): vendor/name
Description []: // leave empty
Author: TONYLABS 
Minimum Stability []: // leave empty if not specified
License []: // leave empty if not specified
Would you like to define your dependencies (require) interactively [yes]? no
Would you like to define your dev dependencies (require-dev) interactively [yes]? no
Do you confirm generation [yes]? yes

Composer Create-Project

$ composer create-project laravel/laravel:^11.0 example-app

Composer Diagnosis

composer diagnose 是 Composer 的一个命令,用于检查当前项目中的依赖管理是否存在潜在问题或配置错误。它可以帮助开发者快速诊断项目中可能影响依赖安装和更新的常见问题。

命令的功能:

  • 检查配置文件:验证 composer.json 文件的语法、结构是否正确,以及是否包含缺失或无效的字段。
  • 检查依赖冲突:分析项目中是否存在依赖版本冲突,确保项目所需的库版本之间是兼容的。
  • 检查 PHP 配置:验证本地环境中的 PHP 设置是否符合项目的需求(例如 PHP 版本、扩展等)。
  • 检查权限问题:确保 vendor 目录及相关文件的权限设置是正确的,以避免在安装或更新依赖时出现权限问题。
  • 检查 Composer 的环境:包括 Composer 是否已正确安装、版本是否为最新等。
  • 检查网络连接:检查 Composer 能否正常连接到仓库(如 packagist.org),确保依赖能被成功下载。

使用示例:

在项目根目录中运行:

$ composer diagnose

常见输出信息:

  • OK:表示一切正常。
  • 警告或错误:详细说明哪些配置或依赖存在问题,例如:
    • PHP 扩展缺失
    • 不兼容的 PHP 版本
    • 依赖版本冲突
    • 网络连接问题(无法连接到镜像仓库或依赖源)

该命令特别适合在调试 Composer 安装失败或依赖问题时使用,可以快速定位可能的原因并提供修复方向。


composer.json

在 Composer 的 require 部分,针对依赖项定义的版本(特别是在 Git 仓库中)通常基于版本控制系统的某些约定(如标签、分支等)。

Previous
Installation