答案:通过配置SSH密钥或个人访问令牌,Composer可安装私有GitLab或Bitbucket仓库的包。1. 使用SSH时,生成密钥并添加公钥到Git账户,composer.json中配置VCS仓库使用git@地址;2. 使用PAT时,在auth.json中设置http-basic认证,composer.json使用HTTPS地址;3. 注意不提交auth.json、确保包名正确、明确指定分支或标签。

要在 Composer 中从私有的 GitLab 或 Bitbucket 仓库安装包,你需要让 Composer 能够访问该私有仓库。这通常通过配置 SSH 密钥或使用个人访问令牌(PAT)来实现。以下是具体步骤。
1. 使用 SSH 访问私有仓库
适用于 GitLab 和 Bitbucket,推荐用于服务器或本地开发环境。步骤:
- 在本地生成 SSH 密钥(如果还没有):
ssh-keygen -t rsa -b 4096 -C "your-email@example.com" - 将公钥(通常是
~/.ssh/id_rsa.pub)添加到你的 GitLab / Bitbucket 账户的 SSH Keys 设置中。 - 在
composer.json中定义仓库:
{
"repositories": [
{
"type": "vcs",
"url": "git@gitlab.com:username/private-package.git"
}
],
"require": {
"username/private-package": "dev-main"
}
}Composer 会使用 SSH 拉取代码,前提是 SSH agent 正常运行并能识别密钥。
2. 使用个人访问令牌(PAT)
适合无法使用 SSH 的环境,如 CI/CD 或共享主机。GitLab 示例:
- 进入 GitLab → Preferences → Access Tokens,创建一个具有
read_repository权限的令牌。 - 在项目根目录的
auth.json文件中保存凭证:
{
"http-basic": {
"gitlab.com": {
"username": "your-username",
"password": "your-access-token"
}
}
}然后在 composer.json 中使用 HTTPS 地址:
{
"repositories": [
{
"type": "vcs",
"url": "https://gitlab.com/username/private-package.git"
}
],
"require": {
"username/private-package": "dev-main"
}
}Composer 会自动使用 auth.json 中的凭据进行认证。
Bitbucket 类似: 创建 App Password 或使用 OAuth Token,并在 auth.json 中配置 bitbucket.org 的 http-basic 认证。
3. 注意事项
-
auth.json不应提交到版本控制,建议加入.gitignore。 - 确保包的
composer.json中有正确的name字段,否则无法 require。 - 分支名需明确指定,如
dev-main、dev-master,或打 tag 使用版本号。 - 首次加载时,Composer 会提示是否信任该 VCS 仓库,输入 yes 即可。
基本上就这些。只要认证配置正确,Composer 就能像拉公开包一样安装私有仓库中的 PHP 包。










