[PHP] 自己維護第三方套件並於專案中使用

Kunyu
3 min readFeb 15, 2024
Photo by Brooke Lark on Unsplash

PHP 新版本發佈時,不定期維護的第三方套件可能不會立即更新,這意味著依賴著此套件的專案不兼容新版本的 PHP,因此無法更新專案的 PHP 版本,那麼除了等待套件開發者更新套件之外,還有一個選擇,那就是在自己的 repository 建立副本,並且讓專案使用。

可以在 Composer Documentation VCS 的介紹中了解到 Composer 已經考慮了套件更新的這個問題,因此提供了方法讓我們可以輕鬆的把第三方套件替換成自己的版本,本篇文章以 FastRoute 套件為例,首先把套件 fork 到自己的 Github,接著進行 clone 之後修改,最後再推上 repository,以下參考內容可以隨意替換,例如也可以不使用 Docker 進行 Composer update。

# Clone the FastRoute repository
git clone https://github.com/KunYuChang/FastRoute.git

# Navigate to the FastRoute directory
cd FastRoute

# Open the FastRoute project in Visual Studio Code
code .

# Create a new branch named 'hotfix' and switch to it
git checkout -b hotifx

# Add all changes to the staging area
git add .

# Commit the changes with a descriptive message
git commit -m 'Update readme with hotfix text'

# Push the changes to the 'hotfix' branch on the remote repository
git push origin hotfix

專案 composer.json

把第三方套件更新推上自己的 repository 之後,接著要對專案的composer.json 進行設定,參考官方範例使用 repositories 來指定自己的修改版本,並且在 require 使用 dev- 開頭作為前綴。

{
"repositories": [{
"type": "vcs",
"url": "https://github.com/KunYuChang/FastRoute.git"
}],
"require": {
"nikic/fast-route": "dev-hotfix"
}
}

composer.json 設定好之後,進行更新,最後到 vendor 對套件進行確認。

# Assuming 'docker compose exec app composer update' is a command to update dependencies using Docker Compose, execute it.
docker compose exec app composer update

--

--