PHP项目Laravel事件缓存清理时机

wen PHP项目 3

本文目录导读:

PHP项目Laravel事件缓存清理时机

  1. 事件映射变更后
  2. 部署流程中
  3. 开发环境
  4. 运行时动态清理
  5. 监控文件变化自动清理
  6. 最佳实践建议
  7. 性能优化建议
  8. 监控与日志

在Laravel项目中,事件缓存清理的时机主要取决于你的具体需求和项目架构,以下是几种常见的清理时机和策略:

事件映射变更后

当你修改了 EventServiceProvider 中的事件映射时:

// app/Providers/EventServiceProvider.php
protected $listen = [
    // 新增或修改事件映射
    OrderShipped::class => [
        SendOrderNotification::class,
        UpdateOrderStatus::class, // 新增监听器
    ],
];

立即清理:

php artisan event:clear
php artisan event:cache

部署流程中

在CI/CD部署脚本中添加:

# deploy.sh 或 CI/CD 配置中
php artisan down --retry=60
php artisan event:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
# 部署新代码
git pull origin main
composer install --no-dev --optimize-autoloader
php artisan migrate --force
# 重新生成缓存
php artisan config:cache
php artisan route:cache
php artisan event:cache
php artisan up

开发环境

在开发过程中,建议在 .env 文件中设置:

APP_ENV=local
APP_DEBUG=true

并在 EventServiceProvider 中禁用缓存:

public function boot()
{
    parent::boot();
    // 开发环境不缓存事件
    if (app()->environment('local')) {
        $this->app->make('events')->clearResolvedInstance('events');
    }
}

运行时动态清理

在某些情况下需要手动触发清理:

// 需要手动清理时
Artisan::call('event:clear');
// 或者在代码中直接清除缓存
Cache::forget('events');

监控文件变化自动清理

使用 Laravel Mix 或 Vite 配置自动监听:

// vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
    ],
    server: {
        watch: {
            paths: ['app/**/*.php'],
            // 检测到文件变化时自动清理事件缓存
            onFileChange: () => {
                exec('php artisan event:clear');
            }
        }
    }
});

最佳实践建议

A. 创建自定义命令包装

// app/Console/Commands/ClearAllCaches.php
class ClearAllCaches extends Command
{
    protected $signature = 'cache:clear-all';
    protected $description = 'Clear all application caches';
    public function handle()
    {
        $this->call('event:clear');
        $this->call('config:clear');
        $this->call('route:clear');
        $this->call('view:clear');
        $this->call('cache:clear');
        $this->info('All caches cleared successfully!');
    }
}

B. 部署脚本示例

# .github/workflows/deploy.yml
name: Deploy
on:
  push:
    branches: [ main ]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Deploy to server
        uses: appleboy/ssh-action@v1.0.3
        with:
          script: |
            cd /var/www/project
            php artisan down
            git pull origin main
            composer install --no-dev --optimize-autoloader
            php artisan migrate --force
            # 清理缓存
            php artisan event:clear
            php artisan config:cache
            php artisan route:cache
            php artisan up

C. 事件版本控制

// app/Providers/AppServiceProvider.php
public function boot()
{
    // 检查是否需要清理事件缓存
    $cacheVersionFile = base_path('bootstrap/cache/event_version.txt');
    if (file_exists($cacheVersionFile)) {
        $lastVersion = file_get_contents($cacheVersionFile);
        $currentCommit = exec('git rev-parse --short HEAD');
        if ($lastVersion !== $currentCommit) {
            $this->app->make('events')->clearResolvedInstance('events');
            Artisan::call('event:clear');
            file_put_contents($cacheVersionFile, $currentCommit);
        }
    }
}

性能优化建议

  1. 生产环境:只在部署时清理并重建缓存
  2. 开发环境:禁用缓存或频繁清理
  3. 使用缓存标签
    // EventServiceProvider.php
    public function boot()
    {
     if (config('app.env') === 'production') {
         $this->app->make('events')->listeners = collect(
             $this->app->make('events')->listeners
         )->map(function ($listeners) {
             return $listeners;
         })->all();
     }
    }

监控与日志

// app/Providers/EventServiceProvider.php
public function boot()
{
    parent::boot();
    // 记录缓存清理操作
    $this->app['log']->info('Event cache cleared at: ' . now());
}

最重要的清理时机:

  • 代码部署后立即执行
  • 修改事件映射后
  • 开发环境切换到生产环境时
  • 使用 Docker 容器重建时

建议策略:

# 每次都执行的操作
php artisan event:clear
php artisan event:cache

如果采用 Docker,可以在 Dockerfile 或 docker-compose.yml 中添加:

# docker/docker-compose.yml
app:
  build:
    context: .
    args:
      - BUILD_ENV=production
  command: >
    sh -c "php artisan event:clear && 
           php artisan event:cache && 
           php-fpm"

这样可以确保每次容器重建时都会自动清理并重新生成事件缓存。

抱歉,评论功能暂时关闭!