Composer 高级特性 #

私有仓库 #

VCS 仓库 #

从版本控制系统安装私有包:

json
{
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/company/private-package"
        }
    ],
    "require": {
        "company/private-package": "^1.0"
    }
}

Git 仓库 #

直接指定 Git 仓库:

json
{
    "repositories": [
        {
            "type": "git",
            "url": "https://github.com/company/private-package.git"
        }
    ]
}

SVN 仓库 #

json
{
    "repositories": [
        {
            "type": "svn",
            "url": "svn://example.com/private-package",
            "trunk-path": "trunk",
            "branches-path": "branches",
            "tags-path": "tags"
        }
    ]
}

本地路径仓库 #

用于开发本地包:

json
{
    "repositories": [
        {
            "type": "path",
            "url": "../my-package",
            "options": {
                "symlink": true
            }
        }
    ],
    "require": {
        "my/package": "*"
    }
}

选项说明:

选项 说明
symlink 创建符号链接(默认 true)
relative 使用相对路径
versions 指定版本

Satis 私有仓库 #

搭建私有 Packagist:

安装 Satis #

bash
composer create-project composer/satis --keep-vcs

配置 satis.json #

json
{
    "name": "My Private Repository",
    "homepage": "https://satis.example.com",
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/company/private-package-1"
        },
        {
            "type": "vcs",
            "url": "https://github.com/company/private-package-2"
        }
    ],
    "require-all": true,
    "archive": {
        "directory": "dist",
        "format": "zip",
        "skip-dev": true
    }
}

构建 #

bash
php bin/satis build satis.json web/

使用 #

json
{
    "repositories": [
        {
            "type": "composer",
            "url": "https://satis.example.com"
        }
    ]
}

Toran Proxy #

企业级私有仓库代理:

json
{
    "repositories": [
        {
            "type": "composer",
            "url": "https://toran.example.com/repo/private"
        }
    ]
}

认证配置 #

GitHub Token #

bash
# 配置 GitHub OAuth Token
composer config -g github-oauth.github.com your-token

# 或使用环境变量
export COMPOSER_GITHUB_TOKEN=your-token

GitLab Token #

bash
composer config -g gitlab-oauth.gitlab.com your-token

HTTP Basic Auth #

bash
composer config -g http-basic.example.org username password

在 composer.json 中配置 #

json
{
    "config": {
        "http-basic": {
            "example.org": {
                "username": "user",
                "password": "pass"
            }
        }
    }
}

平台配置 #

平台包 #

Composer 支持以下平台包:

类型 示例 说明
PHP php PHP 版本
扩展 ext-* PHP 扩展
lib-* 系统库
Composer composer Composer 版本
Composer 插件 API composer-plugin-api 插件 API 版本

要求平台包 #

json
{
    "require": {
        "php": "^8.1",
        "ext-json": "*",
        "ext-pdo": "*",
        "ext-mbstring": "*",
        "lib-curl": "*"
    }
}

模拟平台包 #

在开发环境模拟生产环境:

json
{
    "config": {
        "platform": {
            "php": "8.1.0",
            "ext-something": "1.0.0"
        }
    }
}

检查平台要求 #

bash
# 检查平台要求
composer check-platform-reqs

# 输出示例
ext-json     8.1.0    required by your project
ext-mbstring 8.1.0    required by your project
php          8.1.0    required by your project

性能优化 #

安装优化 #

使用 --prefer-dist #

bash
# 优先使用压缩包(默认)
composer install --prefer-dist

并行下载(Composer 2.x) #

Composer 2.x 默认启用并行下载。

使用缓存 #

bash
# 查看缓存目录
composer config cache-dir

# 清理缓存
composer clear-cache

自动加载优化 #

开发环境 #

bash
composer dump-autoload

生产环境 #

bash
# 优化自动加载
composer dump-autoload --optimize

# 权威类映射(更快)
composer dump-autoload --classmap-authoritative

# APCu 缓存
composer dump-autoload --apcu

生产环境安装 #

bash
# 推荐的生产环境命令
composer install \
    --no-dev \
    --optimize-autoloader \
    --classmap-authoritative \
    --no-interaction \
    --no-progress \
    --prefer-dist

配置优化 #

json
{
    "config": {
        "optimize-autoloader": true,
        "classmap-authoritative": true,
        "apcu-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    }
}

使用国内镜像 #

bash
# 全局配置
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

# 项目配置
composer config repo.packagist composer https://mirrors.aliyun.com/composer/

插件系统 #

安装插件 #

bash
composer require composer-plugin/plugin-name

开发插件 #

创建插件 #

php
<?php
namespace MyVendor\Composer;

use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;

class MyPlugin implements PluginInterface
{
    public function activate(Composer $composer, IOInterface $io)
    {
        $io->write("MyPlugin activated!");
    }

    public function deactivate(Composer $composer, IOInterface $io)
    {
    }

    public function uninstall(Composer $composer, IOInterface $io)
    {
    }
}

插件配置 #

json
{
    "name": "my-vendor/composer-plugin",
    "type": "composer-plugin",
    "extra": {
        "class": "MyVendor\\Composer\\MyPlugin"
    },
    "require": {
        "composer-plugin-api": "^2.0"
    }
}

Capabilities #

Command Provider #

php
<?php
namespace MyVendor\Composer;

use Composer\Plugin\Capability\CommandProvider as CommandProviderCapability;

class CommandProvider implements CommandProviderCapability
{
    public function getCommands()
    {
        return [
            new MyCommand()
        ];
    }
}

自定义命令 #

php
<?php
namespace MyVendor\Composer;

use Composer\Command\BaseCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class MyCommand extends BaseCommand
{
    protected function configure()
    {
        $this->setName('my-command');
        $this->setDescription('My custom command');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln("My command executed!");
        return 0;
    }
}

注册 Capability #

json
{
    "extra": {
        "class": "MyVendor\\Composer\\MyPlugin",
        "plugin-modifies-downloads": true,
        "plugin-modifies-install-path": true,
        "composer-plugin": {
            "command-provider": "MyVendor\\Composer\\CommandProvider"
        }
    }
}

自定义安装器 #

创建安装器 #

php
<?php
namespace MyVendor\Composer;

use Composer\Installer\LibraryInstaller;
use Composer\Package\PackageInterface;

class CustomInstaller extends LibraryInstaller
{
    public function getInstallPath(PackageInterface $package)
    {
        $type = $package->getType();
        
        if ($type === 'my-custom-type') {
            return 'custom/' . $package->getPrettyName();
        }
        
        return parent::getInstallPath($package);
    }

    public function supports($packageType)
    {
        return $packageType === 'my-custom-type';
    }
}

注册安装器 #

php
<?php
namespace MyVendor\Composer;

use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
use Composer\Plugin\Capable;

class InstallerPlugin implements PluginInterface, Capable
{
    public function activate(Composer $composer, IOInterface $io)
    {
    }

    public function getCapabilities()
    {
        return [
            'Composer\Plugin\Capability\InstallerProvider' => 'MyVendor\Composer\InstallerProvider'
        ];
    }
}
php
<?php
namespace MyVendor\Composer;

use Composer\Plugin\Capability\InstallerProvider;

class InstallerProvider implements InstallerProvider
{
    public function getInstallers()
    {
        return [
            new CustomInstaller()
        ];
    }
}

版本管理 #

版本别名 #

json
{
    "extra": {
        "branch-alias": {
            "dev-master": "2.0-dev",
            "dev-develop": "3.0-dev"
        }
    }
}

内部版本 #

json
{
    "require": {
        "monolog/monolog": "dev-feature as 1.2.3"
    }
}

环境变量 #

可用环境变量 #

变量 说明
COMPOSER 指定 composer.json 路径
COMPOSER_ROOT_VERSION 根包版本
COMPOSER_VENDOR_DIR vendor 目录路径
COMPOSER_BIN_DIR bin 目录路径
COMPOSER_CACHE_DIR 缓存目录
COMPOSER_HOME Composer 主目录
COMPOSER_MEMORY_LIMIT 内存限制
COMPOSER_PROCESS_TIMEOUT 进程超时
COMPOSER_GITHUB_TOKEN GitHub Token
COMPOSER_GITLAB_TOKEN GitLab Token
COMPOSER_NO_INTERACTION 非交互模式
COMPOSER_ALLOW_SUPERUSER 允许超级用户

使用示例 #

bash
# 指定 composer.json 路径
COMPOSER=composer.prod.json composer install

# 设置内存限制
COMPOSER_MEMORY_LIMIT=-1 composer update

# 设置 vendor 目录
COMPOSER_VENDOR_DIR=lib composer install

# 设置 bin 目录
COMPOSER_BIN_DIR=bin composer install

依赖版本覆盖 #

使用 overrides #

json
{
    "require": {
        "monolog/monolog": "^2.0"
    },
    "config": {
        "platform": {
            "php": "8.1.0"
        }
    },
    "extra": {
        "overrides": {
            "monolog/monolog": "2.9.2"
        }
    }
}

下载器自定义 #

自定义下载器 #

php
<?php
namespace MyVendor\Composer;

use Composer\Downloader\DownloaderInterface;
use Composer\Package\PackageInterface;
use Composer\Downloader\ChangeReportInterface;

class CustomDownloader implements DownloaderInterface, ChangeReportInterface
{
    public function download(PackageInterface $package, $path, PackageInterface $prevPackage = null)
    {
    }

    public function prepare($type, PackageInterface $package, $path, PackageInterface $prevPackage = null)
    {
    }

    public function cleanup($type, PackageInterface $package, $path, PackageInterface $prevPackage = null)
    {
    }

    public function install(PackageInterface $package, $path)
    {
    }

    public function update(PackageInterface $initial, PackageInterface $target, $path)
    {
    }

    public function remove(PackageInterface $package, $path)
    {
    }

    public function getInstallationSource()
    {
    }

    public function setInstallationSource($source)
    {
    }

    public function getLocalChanges(PackageInterface $package, $path)
    {
    }
}

依赖解析算法 #

解析流程 #

text
composer.json
    │
    ├── 收集所有依赖
    │   ├── require
    │   ├── require-dev
    │   └── 子依赖
    │
    ├── 构建依赖图
    │   └── 递归解析
    │
    ├── 解决冲突
    │   ├── 版本约束
    │   ├── 稳定性
    │   └── 平台要求
    │
    ├── 选择版本
    │   ├── 最新兼容版本
    │   └── 最小版本
    │
    └── 生成 composer.lock

冲突解决 #

bash
# 查看依赖树
composer show -t

# 查看为什么需要某个包
composer why vendor/package

# 查看为什么不能安装某个版本
composer prohibits vendor/package 2.0

# 强制解决
composer update --with-all-dependencies

CI/CD 集成 #

GitHub Actions #

yaml
name: CI

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    
    strategy:
      matrix:
        php: ['8.1', '8.2', '8.3']
    
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: ${{ matrix.php }}
          coverage: xdebug
      
      - name: Validate composer.json
        run: composer validate --strict
      
      - name: Install dependencies
        run: composer install --prefer-dist --no-progress --no-suggest
      
      - name: Run tests
        run: composer test
      
      - name: Run static analysis
        run: composer stan

GitLab CI #

yaml
stages:
  - test
  - deploy

test:
  stage: test
  image: composer:2
  script:
    - composer install --prefer-dist --no-progress --no-interaction
    - composer test
    - composer stan

deploy:
  stage: deploy
  image: composer:2
  script:
    - composer install --no-dev --optimize-autoloader --no-interaction
    - php artisan deploy
  only:
    - main

Jenkins #

groovy
pipeline {
    agent any
    
    stages {
        stage('Install') {
            steps {
                sh 'composer install --prefer-dist --no-progress --no-interaction'
            }
        }
        
        stage('Test') {
            steps {
                sh 'composer test'
            }
        }
        
        stage('Static Analysis') {
            steps {
                sh 'composer stan'
            }
        }
    }
}

故障排除 #

调试模式 #

bash
# 详细输出
composer install -vvv

# 分析依赖
composer install --profile

# 检查平台要求
composer check-platform-reqs

# 诊断
composer diagnose

常见问题 #

内存不足 #

bash
COMPOSER_MEMORY_LIMIT=-1 composer update

超时 #

bash
COMPOSER_PROCESS_TIMEOUT=600 composer install

网络问题 #

bash
# 使用代理
composer config -g http-proxy http://proxy:8080

# 使用镜像
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

权限问题 #

bash
# 修改权限
sudo chown -R $USER:$USER ~/.composer
sudo chown -R $USER:$USER vendor/

下一步 #

现在你已经掌握了高级特性,接下来学习 最佳实践 了解如何在项目中正确使用 Composer!

最后更新:2026-03-28