Composer Scripts 是 composer.json 中 "scripts" 字段定义的命令别名,用于在部署中执行清理、编译等轻量操作;它不替代 CI/CD 工具,而是作为项目级可复现钩子,在 composer install 后自动触发 cache 清理与 temp 文件删除。
Composer Scripts 是 composer.json 中 "scripts" 字段定义的一组命令别名,它们不是构建工具,但能被 composer install、composer update 或手动调用(如 composer run-script)触发。在部署阶段,它常被用来衔接「安装依赖」和「服务启动」之间的清理、编译、权限修复等轻量操作。
关键点在于:它不替代 CI/CD 工具(如 GitHub Actions、Deployer),而是作为项目级的、可复现的钩子存在。如果你的部署流程靠 git pull && composer install 驱动,那 Scripts 就是最自然的清理入口。
以 Laravel 或 Symfony 风格项目为例,缓存和临时文件通常分布在:storage/cache/、bootstrap/cache/、var/cache/、var/log/(Symfony)或 storage/logs/(Laravel)。Composer 本身不清理这些,需靠脚本调用系统命令或框架命令。
在 composer.json 的 "scripts" 下添加:
"scripts": {
"post-install-cmd": [
"@clear-cache",
"@clear-temp"
],
"clear-cache
": "if [ -d 'bootstrap/cache' ]; then rm -rf bootstrap/cache/*; fi && if [ -d 'storage/cache' ]; then find storage/cache -type f -delete; fi",
"clear-temp": "if [ -d 'storage/framework/views' ]; then rm -rf storage/framework/views/*; fi && if [ -d 'storage/framework/sessions' ]; then find storage/framework/sessions -type f -mmin +60 -delete; fi"
}
说明:
post-install-cmd 在每次 composer install 后自动执行,适合部署时触发clear-cache 优先清空 bootstrap/cache/(Laravel 的 compiled.php 等),再安全清理 storage/cache/ 中的键值缓存文件clear-temp 清理视图缓存和过期会话(-mmin +60 表示修改时间超 60 分钟的文件),避免误删活跃会话[ -d '...' ],防止在非标准目录结构下报错中断因为这些命令依赖框架完整加载,而 composer install 执行时,vendor/autoload.php 刚生成,APP_ENV、APP_DEBUG 等环境变量往往未就位,框架引导失败会导致命令退出并报错(如 Class 'App\Providers\AppServiceProvider' not found)。
更稳妥的做法是:只用 shell 命令清理物理文件,把框架级缓存重建留给应用首次请求(Laravel 自动重建 bootstrap/cache/config.php)或后续健康检查步骤。
如果你坚持用框架命令,必须确保:
.env 或部署脚本注入APP_KEY 已存在(否则 Laravel 无法解密配置)--no-interaction 和 --quiet 避免交互阻塞|| true 容错(如 php artisan cache:clear || true),否则失败会中断整个 composer install
Linux 和 macOS 的 find 语法一致,但 Windows(Git Bash 除外)不原生支持。若部署目标含 Windows,应避免依赖 find,改用 rm -rf 或分拆为 PHP 脚本。
另一个容易被忽略的是权限问题:如果部署用户和 Web 用户不同(如部署用 deploy,Web 用 www-data),直接 rm -rf 可能导致后续写入失败。建议清理后补一句 chown -R www-data:www-data storage/(仅限 Linux)。
最后提醒:Composer Scripts 不支持条件判断(如 if $ENV == 'prod'),所有逻辑必须硬编码或委托给外部脚本。复杂流程(如备份旧缓存、校验磁盘空间)请移出 Composer,交给部署工具处理。
# 报错
# linux
# windows
# php
# github
# 的是
# 它不
# 首次
# 为例
# 它在
# 如果你
# 不支持
# 一句
# 仅限
# class
# js
# console
# laravel
# json
# composer
# if
# bootstrap
# git
# var
# 委托
# macos
# bash
# symfony