Laravel 12 生态系统:从扩展包到微服务

摘要

本文深入解析 Laravel 12 的企业级生态系统,涵盖官方扩展包的架构设计与最佳实践、社区扩展包的专业集成、现代前端框架的深度融合、云原生服务的无缝对接,以及微服务架构的完整实施方案。通过技术深度分析、性能基准测试、架构设计指南和企业级最佳实践,为专业开发者提供构建完整 Laravel 技术栈的综合参考。

本文面向需要构建大规模、高性能 Laravel 应用的专业开发者,重点关注生态系统组件的架构设计、性能优化、安全最佳实践和可扩展性,帮助您构建具备企业级可靠性的 Laravel 技术解决方案。

1. Laravel 生态系统概述

Laravel 12 拥有一个丰富的生态系统,从官方扩展包到社区贡献的组件,为开发者提供了全面的工具集。

1.1 核心生态组件

  • 官方扩展包:Sanctum、Passport、Horizon、Telescope、Dusk 等
  • 社区扩展包:Spatie、Laravel-Excel、Laravel-ide-helper 等
  • 前端集成:Laravel Mix、Vite、Livewire、Inertia.js
  • 开发工具:Laravel Valet、Laravel Homestead、Laravel Sail
  • 云服务:Laravel Vapor、Laravel Forge
  • 数据库工具:Laravel Scout、Laravel Cashier

1.2 生态系统的价值

  • 加速开发:现成的组件和工具减少重复开发
  • 提高质量:经过验证的扩展包保证代码质量
  • 降低成本:开源组件减少开发和维护成本
  • 社区支持:活跃的社区提供技术支持和解决方案

2. 官方扩展包使用

Laravel 12 提供了多个官方扩展包,解决常见的开发问题。

2.1 Laravel Sanctum

Sanctum 提供了轻量级的 API 认证解决方案,适用于 SPA、移动应用和简单的令牌认证场景。作为 Laravel 12 中推荐的 API 认证方案,Sanctum 采用无状态令牌机制,支持细粒度的令牌权限控制和过期管理。

安装与配置

1
2
3
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

高级配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// config/sanctum.php
return [
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ',' . parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),

'guard' => ['web'],

'expiration' => null, // 令牌永不过期

'middleware' => [
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
],

'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),

'persistent_grants' => [
'enabled' => true,
'expiration' => null,
],
];

企业级使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 1. 令牌权限控制
$user = User::find(1);
$token = $user->createToken('api-token', ['read:users', 'write:posts'])->plainTextToken;

// 2. 令牌过期管理
$token = $user->createToken('temporary-token', [], now()->addHours(24))->plainTextToken;

// 3. 令牌撤销
$user->tokens()->where('name', 'api-token')->delete();

// 4. 中间件保护
Route::middleware(['auth:sanctum', 'abilities:read:users'])->get('/admin/users', function (Request $request) {
return User::all();
});

// 5. 自定义守卫
// config/auth.php
'guards' => [
'api' => [
'driver' => 'sanctum',
'provider' => 'users',
],
],

// 6. 速率限制集成
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
Route::get('/user', function (Request $request) {
return $request->user();
});
});

性能优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 1. 令牌缓存
// app/Providers/AppServiceProvider.php
use Laravel\Sanctum\PersonalAccessToken;

public function boot()
{
PersonalAccessToken::retrieved(function ($token) {
cache()->put(
"sanctum_token_{$token->token}",
$token,
now()->addMinutes(60)
);
});
}

// 2. 批量令牌管理
$tokens = $user->tokens()->where('name', 'like', 'api-%')->get();
$tokens->each(function ($token) {
if ($token->created_at->lt(now()->subMonths(3))) {
$token->delete();
}
});

2.2 Laravel Passport

Passport 提供了完整的 OAuth2 服务器实现,适用于需要复杂认证流程的企业级应用,支持授权码、客户端凭证、密码授权和刷新令牌等多种 OAuth2 流程。作为 Laravel 12 中处理复杂 API 认证的解决方案,Passport 提供了完整的令牌管理、作用域控制和客户端管理功能。

安装与配置

1
2
3
4
composer require laravel/passport
php artisan vendor:publish --provider="Laravel\Passport\PassportServiceProvider"
php artisan migrate
php artisan passport:install

高级配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// config/passport.php
return [
'client_uuids' => true,
'personal_access_client' => [
'id' => env('PASSPORT_PERSONAL_ACCESS_CLIENT_ID'),
'secret' => env('PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET'),
],
'password_grant_client' => [
'id' => env('PASSPORT_PASSWORD_GRANT_CLIENT_ID'),
'secret' => env('PASSPORT_PASSWORD_GRANT_CLIENT_SECRET'),
],
'token_expires_in' => Carbon::now()->addDays(15),
'refresh_token_expires_in' => Carbon::now()->addDays(30),
'throttle' => [
'max_attempts' => 60,
'decay_minutes' => 1,
],
];

企业级使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// 1. 作用域管理
Passport::tokensCan([
'read-users' => 'Read user information',
'write-users' => 'Create and update users',
'read-posts' => 'Read posts',
'write-posts' => 'Create and update posts',
]);

// 2. 客户端管理
$client = Passport::client()->create([
'user_id' => null,
'name' => 'Third Party App',
'redirect' => 'https://third-party-app.com/callback',
'personal_access_client' => false,
'password_client' => false,
'revoked' => false,
]);

// 3. 令牌管理
$user = User::find(1);

// 创建带作用域的令牌
$token = $user->createToken('api-token', ['read-users', 'write-posts'])->accessToken;

// 刷新令牌
$refreshToken = $user->createToken('refresh-token')->refreshToken;

// 4. 中间件保护
Route::middleware(['auth:api', 'scopes:read-users'])->get('/admin/users', function (Request $request) {
return User::all();
});

// 5. 自定义令牌过期
Passport::tokensExpireIn(now()->addDays(7));
Passport::refreshTokensExpireIn(now()->addDays(30));
Passport::personalAccessTokensExpireIn(now()->addMonths(6));

// 6. 令牌撤销
$tokenId = $user->tokens()->where('name', 'api-token')->first()->id;
Passport::revokeAccessToken($tokenId);

// 7. 授权服务器扩展
Passport::tokensRevokedCallback(function ($tokenId, $userId) {
// 令牌撤销回调
Log::info('Token revoked', ['token_id' => $tokenId, 'user_id' => $userId]);
});

性能优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 1. 令牌缓存
// app/Providers/AppServiceProvider.php
use Laravel\Passport\Token;

public function boot()
{
Token::retrieved(function ($token) {
cache()->put(
"passport_token_{$token->id}",
$token,
now()->addMinutes(30)
);
});
}

// 2. 批量令牌清理
// 定期清理过期令牌
Artisan::command('passport:clean', function () {
$expiredTokens = Token::where('expires_at', '<', now())->get();
$expiredTokens->each->delete();

$this->info('Expired tokens cleaned successfully');
})->purpose('Clean expired Passport tokens');

// 3. 数据库优化
// 为 tokens 表添加索引
Schema::table('oauth_access_tokens', function (Blueprint $table) {
$table->index('user_id');
$table->index('client_id');
$table->index('expires_at');
});

2.3 Laravel Horizon

Horizon 提供了队列监控和管理的仪表板,是处理后台任务的企业级解决方案。作为 Laravel 12 中推荐的队列管理工具,Horizon 提供了实时队列监控、任务统计、队列平衡和自动缩放等高级功能,支持多环境配置和团队协作。

安装与配置

1
2
3
composer require laravel/horizon
php artisan vendor:publish --provider="Laravel\Horizon\HorizonServiceProvider"
php artisan migrate

高级配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// config/horizon.php
return [
'use' => 'default',

'environments' => [
'production' => [
'supervisor-1' => [
'connection' => 'redis',
'queue' => ['default', 'high', 'low'],
'balance' => 'auto',
'maxProcesses' => 10,
'maxTime' => 3600,
'maxJobs' => 10000,
'memory' => 128,
'tries' => 3,
'timeout' => 60,
],
],
'local' => [
'supervisor-1' => [
'connection' => 'redis',
'queue' => ['default'],
'balance' => 'simple',
'maxProcesses' => 3,
'maxTime' => 0,
'maxJobs' => 0,
'memory' => 64,
'tries' => 3,
'timeout' => 60,
],
],
],

'balanceMaxShift' => 1,
'balanceCooldown' => 3,

'queueWaitTimeout' => 60,

'metrics' => [
'trim' => [
'recent' => 60,
'metrics' => 1440,
'jobs' => 10080,
],
],

'fast_termination' => false,

'memory_limit' => 128,
];

企业级使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// 1. 队列优先级
// 定义队列优先级
$job = new ProcessPodcast($podcast);

// 分发到高优先级队列
dispatch($job)->onQueue('high');

// 分发到低优先级队列
dispatch($job)->onQueue('low');

// 2. 任务监控
// 自定义监控面板
Horizon::routeMailNotificationsTo('dev@example.com');
Horizon::routeSlackNotificationsTo('slack-webhook-url', '#horizon');

// 3. 任务超时和重试
// 自定义任务超时
class ProcessPodcast implements ShouldQueue
{
public $timeout = 120; // 2分钟
public $tries = 5;

public function backoff()
{
return [1, 5, 10, 30, 60]; // 指数退避
}
}

// 4. 队列平衡策略
// 自动平衡
Horizon::nightly()->scale(
minProcesses: 1,
maxProcesses: 10,
balance: 'auto'
);

// 5. 健康检查
// 添加到健康检查
Route::get('/health/horizon', function () {
$status = Horizon::health();
return response()->json($status, $status['status'] === 'ok' ? 200 : 503);
});

// 6. 限流
// 任务限流
Redis::funnel('podcast-import')->limit(10)->then(function () {
// 执行导入任务
dispatch(new ImportPodcast($podcast));
}, function () {
// 限流时的处理
return redirect()->back()->with('error', 'Too many imports in progress');
});

性能优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 1. 队列工作器优化
// config/horizon.php
'supervisor-1' => [
'connection' => 'redis',
'queue' => ['default', 'high', 'low'],
'balance' => 'auto', // auto, simple, false
'maxProcesses' => 10,
'minProcesses' => 2,
'balanceMaxShift' => 1,
'balanceCooldown' => 3,
],

// 2. 内存管理
// 限制工作器内存使用
'memory' => 128, // MB

// 3. 任务批处理
// 批处理大型任务
$batch = Bus::batch([
new ProcessPodcast($podcast1),
new ProcessPodcast($podcast2),
new ProcessPodcast($podcast3),
])->then(function (Batch $batch) {
// 所有任务完成
Log::info('All podcasts processed');
})->catch(function (Batch $batch, Throwable $e) {
// 发生错误
Log::error('Podcast processing failed', ['error' => $e->getMessage()]);
})->finally(function (Batch $batch) {
// 无论成功失败都会执行
Log::info('Podcast processing completed');
})->dispatch();

// 4. 队列监控告警
// 自定义告警阈值
Horizon::when(
function ($payload) {
return $payload['queue'] === 'high' && $payload['failed'] > 5;
},
function ($payload) {
// 发送告警
Mail::to('dev@example.com')->send(new QueueFailureAlert($payload));
}
);

2.4 Laravel Telescope

Telescope 提供了强大的调试助手,是 Laravel 12 中监控应用性能、排查问题的企业级工具。作为专业开发者的调试利器,Telescope 提供了实时监控请求、队列、数据库查询、缓存操作等核心指标的能力,支持自定义监控规则和告警机制,帮助团队快速定位和解决生产环境中的性能瓶颈和错误。

安装与配置

1
2
3
composer require laravel/telescope --dev
php artisan vendor:publish --provider="Laravel\Telescope\TelescopeServiceProvider"
php artisan migrate

高级配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// config/telescope.php
return [
'path' => env('TELESCOPE_PATH', 'telescope'),

'storage' => [
'driver' => env('TELESCOPE_DRIVER', 'database'),
'database' => [
'connection' => env('DB_CONNECTION', 'mysql'),
],
],

'watchers' => [
Watchers\CacheWatcher::class => [
'enabled' => env('TELESCOPE_CACHE_WATCHER', true),
],
Watchers\CommandWatcher::class => [
'enabled' => env('TELESCOPE_COMMAND_WATCHER', true),
'ignore' => ['key:generate', 'package:discover'],
],
Watchers\DumpWatcher::class => [
'enabled' => env('TELESCOPE_DUMP_WATCHER', true),
],
Watchers\EventWatcher::class => [
'enabled' => env('TELESCOPE_EVENT_WATCHER', true),
'ignore' => [],
],
Watchers\ExceptionWatcher::class => [
'enabled' => env('TELESCOPE_EXCEPTION_WATCHER', true),
],
Watchers\JobWatcher::class => [
'enabled' => env('TELESCOPE_JOB_WATCHER', true),
'ignore' => [],
],
Watchers\LogWatcher::class => [
'enabled' => env('TELESCOPE_LOG_WATCHER', true),
'level' => 'error',
],
Watchers\MailWatcher::class => [
'enabled' => env('TELESCOPE_MAIL_WATCHER', true),
],
Watchers\ModelWatcher::class => [
'enabled' => env('TELESCOPE_MODEL_WATCHER', true),
'events' => ['eloquent.*'],
],
Watchers\NotificationWatcher::class => [
'enabled' => env('TELESCOPE_NOTIFICATION_WATCHER', true),
],
Watchers\QueryWatcher::class => [
'enabled' => env('TELESCOPE_QUERY_WATCHER', true),
'slow' => env('TELESCOPE_SLOW_QUERY_THRESHOLD', 100),
'max_query_size' => env('TELESCOPE_MAX_QUERY_SIZE', 10000),
],
Watchers\RedisWatcher::class => [
'enabled' => env('TELESCOPE_REDIS_WATCHER', true),
],
Watchers\RequestWatcher::class => [
'enabled' => env('TELESCOPE_REQUEST_WATCHER', true),
'size_limit' => env('TELESCOPE_RESPONSE_SIZE_LIMIT', 64),
'ignore_paths' => ['nova-api/*', 'telescope/*'],
'ignore_methods' => ['HEAD'],
],
Watchers\ScheduleWatcher::class => [
'enabled' => env('TELESCOPE_SCHEDULE_WATCHER', true),
],
],

'limit' => env('TELESCOPE_ENTRIES_LIMIT', 100),

'filter' => [
'enabled' => env('TELESCOPE_FILTER_ENABLED', false),
'tags' => [],
'abilities' => [],
],

'endpoint' => env('TELESCOPE_ENDPOINT', 'telescope/api'),
];

企业级使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// 1. 自定义监控规则
// 注册自定义 watcher
Telescope::registerWatcher(
new class implements Watcher {
public function register($app) {
// 注册监控逻辑
}

public function record($app, array $entries) {
// 记录监控数据
}
}
);

// 2. 性能监控
// 监控慢查询
Telescope::filter(function (IncomingEntry $entry) {
if ($entry->type === EntryType::QUERY) {
return $entry->content['time'] > 500; // 500ms 以上的查询
}
return false;
});

// 3. 安全访问控制
// 自定义访问控制
Telescope::auth(function ($request) {
return $request->user() && $request->user()->hasRole('admin');
});

// 4. 数据清理
// 定期清理 Telescope 数据
Artisan::command('telescope:clean', function () {
$days = $this->ask('How many days of data should we keep?', 7);

Telescope::deleteEntriesOlderThan($days);

$this->info('Telescope data cleaned successfully');
})->purpose('Clean up old Telescope entries');

// 5. 导出与分析
// 导出监控数据
Route::get('/telescope/export', function () {
$entries = Telescope::entries()->latest()->take(1000)->get();
return response()->json($entries);
})->middleware('telescope');

// 6. 集成告警
// 配置异常告警
Telescope::afterStoring(function (IncomingEntry $entry) {
if ($entry->type === EntryType::EXCEPTION) {
// 发送异常通知
Notification::route('slack', env('SLACK_WEBHOOK'))
->notify(new TelescopeExceptionNotification($entry));
}
});

性能优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 1. 生产环境优化
// app/Providers/TelescopeServiceProvider.php
public function register() {
$this->hideSensitiveRequestDetails();

if (app()->environment('production')) {
Telescope::filter(function (IncomingEntry $entry) {
// 只记录错误和慢查询
return $entry->type === EntryType::EXCEPTION ||
($entry->type === EntryType::QUERY && $entry->content['time'] > 1000);
});
}
}

// 2. 存储优化
// 使用 Redis 存储高频数据
'watchers' => [
Watchers\RequestWatcher::class => [
'enabled' => true,
'storage' => 'redis', // 高频数据使用 Redis
],
],

// 3. 批量处理
// 批量记录监控数据
Telescope::batch(function () {
// 批量执行操作
for ($i = 0; $i < 1000; $i++) {
// 业务逻辑
}
});

// 4. 自定义采样率
// 生产环境采样率
if (app()->environment('production')) {
Telescope::shouldRecord(function (IncomingEntry $entry) {
// 只记录 10% 的请求
return rand(1, 100) <= 10;
});
}

3. 社区扩展包使用

社区提供了大量高质量的扩展包,解决各种开发问题。

3.1 Spatie 包

Spatie 是 Laravel 社区最活跃的贡献者之一,提供了众多企业级扩展包。作为 Laravel 12 生态系统中的重要组成部分,Spatie 包以其高质量、高性能和良好的文档支持而闻名,涵盖了权限管理、媒体库、活动日志、数据导出等多个领域的专业解决方案。

Laravel Permission

Laravel Permission 是企业级权限管理的标准解决方案,支持基于角色的访问控制(RBAC)、权限继承、多租户权限隔离等高级特性。

1
2
3
composer require spatie/laravel-permission
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan migrate

高级配置与使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 1. 权限管理
// 定义权限层次结构
Permission::create(['name' => 'view users']);
Permission::create(['name' => 'create users']);
Permission::create(['name' => 'edit users']);
Permission::create(['name' => 'delete users']);

// 创建角色并分配权限
$adminRole = Role::create(['name' => 'admin']);
$adminRole->givePermissionTo(['view users', 'create users', 'edit users', 'delete users']);

$editorRole = Role::create(['name' => 'editor']);
$editorRole->givePermissionTo(['view users', 'edit users']);

// 2. 权限继承
// 创建角色继承关系
$superAdminRole = Role::create(['name' => 'super-admin']);
$superAdminRole->givePermissionTo($adminRole->permissions);

// 3. 多租户支持
// 配置多租户权限
// config/permission.php
return [
'team_model' => App\Models\Team::class,
'user_teams_pivot_table' => 'user_teams',
'team_roles_pivot_table' => 'team_roles',
'team_permissions_pivot_table' => 'team_permissions',
];

// 4. 中间件保护
// 注册中间件
Route::middleware(['role:admin'])->group(function () {
Route::get('/admin', [AdminController::class, 'index']);
});

Route::middleware(['permission:edit articles'])->group(function () {
Route::put('/articles/{id}', [ArticleController::class, 'update']);
});

// 5. 权限缓存
// 启用权限缓存
// config/permission.php
'cache' => [
'expiration_time' => 60 * 24, // 24小时
'key' => 'spatie.permission.cache',
'model_key' => 'permission.model',
'store' => 'default',
],

// 6. 自定义权限检查
// 扩展权限检查
Gate::define('view-dashboard', function ($user) {
return $user->hasPermissionTo('view dashboard') || $user->hasRole('admin');
});

Laravel Media Library

Laravel Media Library 是企业级媒体管理解决方案,支持多文件上传、自动转换、媒体排序、关联管理等高级特性。

1
2
3
composer require spatie/laravel-medialibrary
php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider"
php artisan migrate

高级配置与使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// 1. 媒体库配置
// config/media-library.php
return [
'disk_name' => env('MEDIA_DISK', 'public'),
'path_generator' => Spatie\MediaLibrary\PathGenerator\DefaultPathGenerator::class,
'url_generator' => Spatie\MediaLibrary\UrlGenerator\DefaultUrlGenerator::class,
'queue_name' => null,
'max_file_size' => 1024 * 1024 * 10, // 10MB
'responsive_images' => [
'widths' => [100, 200, 400, 800, 1200],
'quality' => 80,
'format' => 'webp',
],
];

// 2. 媒体转换
// 定义媒体转换
use Spatie\MediaLibrary\MediaCollections\MediaCollection;
use Spatie\MediaLibrary\MediaCollections\File;use Spatie\MediaLibrary\Conversions\Conversion;

class Product extends Model implements HasMedia
{
use InteractsWithMedia;

public function registerMediaCollections(): void
{
$this->addMediaCollection('images')
->acceptsFile(function (File $file) {
return $file->mimeType === 'image/jpeg' || $file->mimeType === 'image/png';
})
->useDisk('s3')
->withResponsiveImages();
}

public function registerMediaConversions(Media $media = null): void
{
$this->addMediaConversion('thumb')
->width(368)
->height(232)
->sharpen(10)
->quality(80);

$this->addMediaConversion('featured')
->width(1200)
->height(630)
->crop('crop-center', 1200, 630)
->quality(85)
->format('webp');
}
}

// 3. 媒体上传与管理
// 上传媒体
$product->addMediaFromRequest('image')
->usingFileName('custom-name.jpg')
->usingName('Custom Name')
->withCustomProperties(['alt' => 'Product image'])
->toMediaCollection('images');

// 批量上传
$product->addMultipleMediaFromRequest(['images'])
->each(function (Media $media) use ($product) {
$media->toMediaCollection('images');
});

// 4. 媒体查询
// 高级媒体查询
$media = $product->media()
->where('collection_name', 'images')
->orderBy('order_column', 'asc')
->get();

// 5. 媒体优化
// 延迟加载媒体
$products = Product::with('media')->get();

// 缓存媒体URL
$cacheKey = "product_{$product->id}_media_urls";
$mediaUrls = cache()->remember($cacheKey, 3600, function () use ($product) {
return [
'thumb' => $product->getFirstMediaUrl('images', 'thumb'),
'featured' => $product->getFirstMediaUrl('images', 'featured'),
];
});

Spatie 其他实用包

Laravel Activity Log
1
2
3
composer require spatie/laravel-activitylog
php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider"
php artisan migrate
1
2
3
4
5
6
7
8
9
// 记录活动
activity()
->performedOn($article)
->causedBy($user)
->withProperties(['ip' => $request->ip()])
->log('updated article');

// 查看活动日志
$activity = activity()->for($article)->get();
Laravel Settings
1
2
3
composer require spatie/laravel-settings
php artisan vendor:publish --provider="Spatie\LaravelSettings\LaravelSettingsServiceProvider"
php artisan migrate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 定义设置类
class GeneralSettings extends Settings
{
public string $site_name;
public string $site_description;
public bool $maintenance_mode;

public static function group(): string
{
return 'general';
}

public static function defaults(): array
{
return [
'site_name' => 'Laravel App',
'site_description' => 'A Laravel application',
'maintenance_mode' => false,
];
}
}

// 使用设置
$settings = app(GeneralSettings::class);
echo $settings->site_name;

// 更新设置
$settings->site_name = 'New Site Name';
$settings->save();

3.2 其他常用扩展包

Laravel Excel

1
composer require maatwebsite/excel
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 导出 Excel
use Maatwebsite\Excel\Concerns\FromCollection;

class UsersExport implements FromCollection
{
public function collection()
{
return User::all();
}
}

// 控制器中使用
public function export()
{
return Excel::download(new UsersExport, 'users.xlsx');
}

Laravel IDE Helper

1
composer require --dev barryvdh/laravel-ide-helper
1
2
3
4
// 生成 IDE 助手文件
php artisan ide-helper:generate
php artisan ide-helper:models
php artisan ide-helper:meta

4. 前端集成

Laravel 12 提供了多种现代化前端集成方案,从传统的 Mix 到现代的 Vite,从全栈框架 Livewire 到单页应用框架 Inertia.js。作为企业级应用的技术栈选择,前端集成需要考虑开发效率、性能优化、团队协作和可维护性等多个维度,为专业开发者提供灵活的前端解决方案。

4.1 Vite 集成

Vite 是 Laravel 12 默认的前端构建工具,提供了更快的开发体验、更高效的构建过程和更现代的前端生态系统集成。作为企业级前端构建解决方案,Vite 支持热模块替换(HMR)、代码分割、Tree Shaking 等高级特性,显著提升开发效率和生产环境性能。

高级配置

1
npm install
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';
import path from 'path';

export default defineConfig({
plugins: [
laravel({
input: [
'resources/css/app.css',
'resources/js/app.js',
],
refresh: {
enabled: true,
paths: ['./resources/views/**', './app/Livewire/**'],
},
}),
vue(),
],
resolve: {
alias: {
'@': path.resolve(__dirname, 'resources/js'),
'components': path.resolve(__dirname, 'resources/js/components'),
'pages': path.resolve(__dirname, 'resources/js/Pages'),
},
},
build: {
outDir: 'public/build',
assetsDir: 'assets',
manifest: true,
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
},
},
rollupOptions: {
output: {
manualChunks: {
vendor: ['vue', 'axios'],
'vue-router': ['vue-router'],
'pinia': ['pinia'],
},
},
},
},
server: {
port: 3000,
hmr: {
host: 'localhost',
},
proxy: {
'^/api': {
target: 'http://localhost:8000',
changeOrigin: true,
},
},
},
});

企业级使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 1. 资源版本控制
// 使用 Vite 清单文件
use Illuminate\Support\Facades\Vite;

// 在视图中使用
<link rel="stylesheet" href="{{ Vite::asset('resources/css/app.css') }}">
<script type="module" src="{{ Vite::asset('resources/js/app.js') }}"></script>

// 2. 环境变量管理
// .env
VITE_APP_NAME="Laravel App"
VITE_API_URL="/api"
VITE_DEBUG=true

// 在前端使用
const appName = import.meta.env.VITE_APP_NAME;
const apiUrl = import.meta.env.VITE_API_URL;

// 3. 多环境配置
// vite.config.js
export default defineConfig(({ mode }) => {
const isProduction = mode === 'production';

return {
// 配置
build: {
sourcemap: !isProduction,
},
};
});

4.2 Livewire

Livewire 提供了全栈框架体验,无需编写 JavaScript 即可构建交互式界面。作为 Laravel 12 中推荐的全栈前端解决方案,Livewire 结合了后端 Laravel 的强大功能和前端框架的交互性,支持组件化开发、实时验证、表单处理等企业级特性。

安装与配置

1
2
composer require livewire/livewire
php artisan livewire:publish --config

高级配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// config/livewire.php
return [
'asset_url' => env('APP_URL', 'http://localhost'),
'app_url' => env('APP_URL', 'http://localhost'),
'prefix' => env('LIVEWIRE_PREFIX', 'livewire'),
'middleware_group' => ['web'],
'temporary_file_upload' => [
'disk' => 'public',
'rules' => ['file' => 'max:10240'], // 10MB
'directory' => 'livewire-tmp',
'storage' => 'local',
],
'render_on_redirect' => false,
'legacy_model_binding' => false,
];

企业级使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
// 1. 组件架构
// 创建高级组件
class UserManagement extends Component
{
use WithPagination;

public $search = '';
public $sortField = 'name';
public $sortDirection = 'asc';
public $selectedUsers = [];
public $perPage = 10;

protected $queryString = [
'search' => ['except' => ''],
'sortField' => ['except' => 'name'],
'sortDirection' => ['except' => 'asc'],
'page' => ['except' => 1],
];

public function updatedSearch()
{
$this->resetPage();
}

public function sortBy($field)
{
if ($this->sortField === $field) {
$this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
} else {
$this->sortField = $field;
$this->sortDirection = 'asc';
}
}

public function deleteSelected()
{
User::whereIn('id', $this->selectedUsers)->delete();
$this->selectedUsers = [];
$this->dispatchBrowserEvent('users-deleted');
}

public function render()
{
$users = User::query()
->when($this->search, function ($query) {
$query->where('name', 'like', '%' . $this->search . '%')
->orWhere('email', 'like', '%' . $this->search . '%');
})
->orderBy($this->sortField, $this->sortDirection)
->paginate($this->perPage);

return view('livewire.user-management', ['users' => $users]);
}
}

// 2. 实时验证
class ContactForm extends Component
{
public $name;
public $email;
public $message;

protected $rules = [
'name' => 'required|min:3',
'email' => 'required|email',
'message' => 'required|min:10',
];

protected $validationAttributes = [
'name' => 'Name',
'email' => 'Email Address',
'message' => 'Message',
];

public function updated($propertyName)
{
$this->validateOnly($propertyName);
}

public function submit()
{
$validatedData = $this->validate();

// 处理表单提交
Contact::create($validatedData);

$this->reset();
$this->dispatchBrowserEvent('form-submitted');
}

public function render()
{
return view('livewire.contact-form');
}
}

// 3. 组件通信
// 父组件
class Dashboard extends Component
{
public $totalUsers = 0;

protected $listeners = ['userAdded' => 'updateUserCount'];

public function updateUserCount()
{
$this->totalUsers = User::count();
}

public function render()
{
return view('livewire.dashboard');
}
}

// 子组件
class UserCreate extends Component
{
public function createUser()
{
// 创建用户
$user = User::create(['name' => 'New User', 'email' => 'new@example.com']);

// 触发事件
$this->emit('userAdded');
}
}

4.3 Inertia.js

Inertia.js 允许使用现代前端框架(如 Vue、React)构建单页应用,同时保持 Laravel 的路由系统。作为 Laravel 12 中构建现代单页应用的推荐方案,Inertia.js 提供了无缝的前后端集成、自动代码分割、服务器端渲染等企业级特性,支持 Vue 3、React 和 Svelte 等主流前端框架。

安装与配置

1
2
composer require inertiajs/inertia-laravel
npm install @inertiajs/inertia @inertiajs/inertia-vue3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 配置中间件
php artisan inertia:middleware

// app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
// ...
\App\Http\Middleware\HandleInertiaRequests::class,
],
];

// 自定义中间件
// app/Http/Middleware/HandleInertiaRequests.php
class HandleInertiaRequests extends Middleware
{
public function share(Request $request): array
{
return array_merge(parent::share($request), [
'auth' => [
'user' => $request->user(),
'roles' => $request->user()?->roles->pluck('name'),
],
'flash' => [
'message' => fn () => $request->session()->get('message'),
'error' => fn () => $request->session()->get('error'),
],
'settings' => [
'site_name' => config('app.name'),
'api_url' => config('app.url') . '/api',
],
]);
}
}

企业级使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
// 1. 控制器集成
use Inertia\Inertia;

class UserController extends Controller
{
public function index(Request $request)
{
$users = User::query()
->when($request->input('search'), function ($query, $search) {
$query->where('name', 'like', '%' . $search . '%');
})
->paginate(10)
->withQueryString();

return Inertia::render('Users/Index', [
'users' => $users,
'filters' => $request->only(['search']),
]);
}

public function create()
{
return Inertia::render('Users/Create', [
'roles' => Role::all(),
]);
}

public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:8',
]);

$user = User::create($validated);

return redirect()->route('users.index')
->with('message', 'User created successfully');
}
}

// 2. 前端组件
// resources/js/Pages/Users/Index.vue
<template>
<div class="container">
<h1>Users</h1>

<div class="mb-4">
<input
v-model="filters.search"
@input="updateFilters"
placeholder="Search users..."
class="form-input"
>
<Link href="/users/create" class="btn btn-primary">
Create User
</Link>
</div>

<div v-if="users.data.length === 0" class="alert alert-info">
No users found
</div>

<table v-else class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users.data" :key="user.id">
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>
<Link :href="`/users/${user.id}/edit`" class="btn btn-sm btn-secondary">
Edit
</Link>
<button @click="deleteUser(user.id)" class="btn btn-sm btn-danger">
Delete
</button>
</td>
</tr>
</tbody>
</table>

<div class="pagination">
<button
v-if="users.links.prev"
@click="$inertia.visit(users.links.prev)"
class="btn btn-sm"
>
Previous
</button>
<button
v-if="users.links.next"
@click="$inertia.visit(users.links.next)"
class="btn btn-sm"
>
Next
</button>
</div>
</div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { usePage, useForm, Link } from '@inertiajs/inertia-vue3';

const { users, filters } = usePage().props;

function updateFilters() {
$inertia.get('/users', filters, {
preserveScroll: true,
preserveState: true,
});
}

function deleteUser(id) {
if (confirm('Are you sure?')) {
$inertia.delete(`/users/${id}`, {
onSuccess: () => {
$inertia.reload({
preserveScroll: true,
});
},
});
}
}
</script>

// 3. 路由集成
// routes/web.php
Route::middleware(['auth'])->group(function () {
Route::resource('users', UserController::class);
Route::resource('posts', PostController::class);
});

// 4. 代码分割
// resources/js/app.js
import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/inertia-vue3';
import { InertiaProgress } from '@inertiajs/progress';

InertiaProgress.init({
color: '#4B5563',
showSpinner: true,
});

createInertiaApp({
resolve: name => {
const pages = import.meta.glob('./Pages/**/*.vue', { eager: false });
return pages[`./Pages/${name}.vue`];
},
setup({ el, app, props, plugin }) {
createApp({ render: () => h(app, props) })
.use(plugin)
.mount(el);
},
});

5. 开发工具

Laravel 12 提供了多种专业开发工具,简化本地开发环境的搭建和管理。作为企业级开发流程的重要组成部分,这些工具支持多环境配置、团队协作、自动化测试和持续集成,为专业开发者提供高效、一致的开发体验。

5.1 Laravel Sail

Sail 提供了基于 Docker 的开发环境,是 Laravel 12 中推荐的跨平台开发环境解决方案。作为企业级开发工具,Sail 支持多容器配置、自定义服务集成、环境变量管理和团队共享配置,确保开发、测试和生产环境的一致性。

安装与配置

1
2
3
composer require laravel/sail --dev
php artisan sail:install
./vendor/bin/sail up

高级配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// 1. 自定义 Docker 服务
// docker-compose.yml
version: '3'

services:
laravel.test:
build:
context: ./vendor/laravel/sail/runtimes/8.2
dockerfile: Dockerfile
args:
WWWGROUP: '${WWWGROUP}'
image: sail-8.2/app
extra_hosts:
- 'host.docker.internal:host-gateway'
ports:
- '${APP_PORT:-80}:80'
environment:
WWWUSER: '${WWWUSER}'
LARAVEL_SAIL: 1
XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}'
XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}'
volumes:
- '.:/var/www/html'
networks:
- sail
depends_on:
- mysql
- redis
- meilisearch
- selenium

mysql:
image: 'mysql/mysql-server:8.0'
ports:
- '${FORWARD_DB_PORT:-3306}:3306'
environment:
MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
MYSQL_ROOT_HOST: "%"
MYSQL_DATABASE: '${DB_DATABASE}'
MYSQL_USER: '${DB_USERNAME}'
MYSQL_PASSWORD: '${DB_PASSWORD}'
MYSQL_ALLOW_EMPTY_PASSWORD: 1
volumes:
- 'sail-mysql:/var/lib/mysql'
- './vendor/laravel/sail/database/mysql/create-testing-database.sql:/docker-entrypoint-initdb.d/10-create-testing-database.sql'
networks:
- sail
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}"]
retries: 3
timeout: 5s

redis:
image: 'redis:alpine'
ports:
- '${FORWARD_REDIS_PORT:-6379}:6379'
volumes:
- 'sail-redis:/data'
networks:
- sail
healthcheck:
test: ["CMD", "redis-cli", "ping"]
retries: 3
timeout: 5s

networks:
sail:
driver: bridge

volumes:
sail-mysql:
driver: local
sail-redis:
driver: local

企业级使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 1. 环境变量管理
# .env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=sail
DB_PASSWORD=password

REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379

# 2. 自定义命令别名
# ~/.bashrc 或 ~/.zshrc
alias sail='[ -f sail ] && sh sail || sh vendor/bin/sail'

# 3. 多环境配置
# 创建测试环境配置
cp .env .env.testing

# 4. 运行测试
sail test

# 5. 数据库管理
sail artisan migrate
sail artisan db:seed

# 6. 性能优化
sail artisan optimize
sail artisan config:cache
sail artisan route:cache

# 7. 团队协作
# 提交 docker-compose.yml 到版本控制
# 团队成员只需运行:
composer install
./vendor/bin/sail up

5.2 Laravel Valet

Valet 提供了轻量级的本地开发环境,是 Laravel 12 中推荐的 macOS 开发环境解决方案。作为专业开发者的本地开发工具,Valet 支持多站点管理、HTTPS 配置、数据库集成和共享站点等企业级特性,为 macOS 用户提供高效、低资源占用的开发环境。

安装与配置

1
2
3
4
composer global require laravel/valet
valet install
cd your-project
valet link

高级配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 1. 多 PHP 版本管理
valet use php@8.2

# 2. HTTPS 配置
valet secure your-project

# 3. 站点组管理
mkdir ~/Sites
cd ~/Sites
valet park

# 4. 自定义域名
valet domain test

# 5. 数据库集成
brew install mysql
valet db create your-project

# 6. 性能优化
valet restart

企业级使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 1. 站点管理
# 查看所有站点
valet sites

# 重启站点
valet restart

# 停止站点
valet stop

# 2. 共享站点
# 生成公开 URL
valet share

# 3. 自定义配置
# 创建站点特定配置
mkdir -p ~/.config/valet/Nginx

# 4. 团队协作
# 配置文件共享
# .valetrc
php=php@8.2
domain=test

# 5. 自动化测试
# 运行 PHPUnit
valet php vendor/bin/phpunit

# 6. 性能监控
# 查看 Valet 状态
valet status

5.3 其他开发工具

Laravel Homestead

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 安装 Homestead
cd ~
git clone https://github.com/laravel/homestead.git Homestead
cd Homestead
bash init.sh

# 配置 Homestead
# ~/.homestead/Homestead.yaml
---
ip: 192.168.10.10
memory: 2048
cpus: 2
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
- ~/.ssh/id_rsa

folders:
- map: ~/Code
to: /home/vagrant/Code

sites:
- map: homestead.test
to: /home/vagrant/Code/Laravel/public

databases:
- homestead

# 启动 Homestead
vagrant up

Laravel Herd

1
2
3
4
5
6
7
# 安装 Herd
# 从官方网站下载并安装

# 基本使用
# 启动 Herd
# 添加项目目录
# 访问项目: http://your-project.test

6. 云服务集成

Laravel 12 提供了与云服务的无缝集成,是企业级应用部署和运维的专业解决方案。作为现代 Laravel 应用的云原生支持,云服务集成涵盖了无服务器部署、服务器管理、容器编排和托管服务等多个维度,为专业开发者提供灵活、可扩展的云部署选项。

6.1 Laravel Vapor

Vapor 是 Laravel 的无服务器部署平台,运行在 AWS Lambda 上。作为 Laravel 12 中推荐的无服务器部署解决方案,Vapor 提供了自动扩缩容、零停机部署、环境隔离和安全管理等企业级特性,支持 PHP 8.2+ 和 Laravel 12 的所有核心功能。

安装与配置

1
2
3
composer require laravel/vapor-cli
vapor login
vapor init

高级配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// vapor.yml
id: 12345
name: laravel-app
region: us-east-1
environments:
production:
memory: 1024
cli-memory: 512
runtime: php-8.2
build:
- 'composer install --no-dev'
- 'php artisan optimize'
- 'php artisan config:cache'
- 'php artisan route:cache'
deploy:
- 'php artisan migrate --force'
- 'php artisan db:seed --force'
domains:
- app.example.com
ssl:
wildcard: false
environment:
APP_ENV: production
APP_DEBUG: false
APP_URL: https://app.example.com
DB_CONNECTION: mysql
DB_HOST: "${vapor:RDS_HOSTNAME}"
DB_PORT: "${vapor:RDS_PORT}"
DB_DATABASE: "${vapor:RDS_DB_NAME}"
DB_USERNAME: "${vapor:RDS_USERNAME}"
DB_PASSWORD: "${vapor:RDS_PASSWORD}"
staging:
memory: 512
cli-memory: 512
runtime: php-8.2
build:
- 'composer install'
- 'php artisan optimize'
deploy:
- 'php artisan migrate --force'
domains:
- staging.example.com
environment:
APP_ENV: staging
APP_DEBUG: true
APP_URL: https://staging.example.com

memory:
use: 1024
cli-memory:
use: 512

企业级使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 1. 环境管理
vapor env:pull production
vapor env:push production

# 2. 数据库管理
vapor db:list
vapor db:backup production

# 3. 缓存管理
vapor cache:clear production

# 4. 队列管理
vapor queue:list
vapor queue:failed production

# 5. 监控与日志
vapor logs production
vapor metrics production

# 6. 安全管理
vapor ssl:list
vapor ssl:renew production

# 7. 部署策略
# 蓝绿部署
vapor deploy production --bluegreen

# 回滚部署
vapor deployments
vapor rollback production 123

# 8. 团队协作
vapor team:add user@example.com
vapor team:list

6.2 Laravel Forge

Forge 是 Laravel 的服务器管理平台,自动化部署和配置。作为 Laravel 12 中推荐的服务器管理解决方案,Forge 提供了一键服务器创建、自动部署、SSL 证书管理和服务器监控等企业级特性,支持 AWS、DigitalOcean、Linode、Google Cloud 等主流云服务商。

安装与配置

1
2
3
4
5
6
7
8
9
10
11
# 1. 注册 Forge 账号
# https://forge.laravel.com

# 2. 连接云服务提供商
# AWS、DigitalOcean、Linode 等

# 3. 创建服务器
# 选择服务器规格和位置

# 4. 创建站点
# 配置域名和根目录

企业级使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 1. 自动化部署
# 配置 GitHub/GitLab 集成
# 设置部署钩子

# 2. 服务器管理
# 查看服务器状态
forge server:status

# 重启服务
forge service:restart nginx
forge service:restart php8.2-fpm

# 3. 数据库管理
forge mysql:create database
forge mysql:user:create username

# 4. SSL 管理
forge ssl:install example.com
forge ssl:renew example.com

# 5. 防火墙配置
forge firewall:allow 22
forge firewall:deny 3306

# 6. 监控与告警
forge monitor:enable
forge alert:create --threshold=80 --metric=cpu

# 7. 团队协作
forge user:add team@example.com
forge user:permission --user=team@example.com --server=123 --permission=deploy

# 8. 负载均衡
# 配置多服务器负载均衡
forge load-balancer:create
forge load-balancer:attach 123

6.3 容器化部署

Docker 和 Kubernetes 是 Laravel 12 中推荐的容器化部署解决方案。作为企业级应用的现代部署方式,容器化部署提供了环境一致性、快速扩缩容、高可用性和多环境管理等企业级特性,支持 CI/CD 集成和自动化运维。

Docker 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Dockerfile
FROM php:8.2-fpm-alpine

WORKDIR /var/www/html

# 安装依赖
RUN apk add --no-cache \
curl \
git \
zip \
unzip \
libpng-dev \
libjpeg-turbo-dev \
libwebp-dev \
freetype-dev \
libxml2-dev \
oniguruma-dev \
sqlite-dev \
postgresql-dev \
redis-dev \
&& docker-php-ext-install \
pdo_mysql \
pdo_pgsql \
pdo_sqlite \
mysqli \
gd \
xml \
mbstring \
opcache \
&& pecl install redis \
&& docker-php-ext-enable redis

# 安装 Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# 复制应用代码
COPY . .

# 安装依赖
RUN composer install --no-dev --optimize-autoloader

# 配置 PHP
COPY php.ini /usr/local/etc/php/conf.d/custom.ini

# 生成密钥
RUN php artisan key:generate

# 配置权限
RUN chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache

EXPOSE 9000

CMD ["php-fpm"]

Kubernetes 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# kubernetes/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: laravel-app
labels:
app: laravel-app
spec:
replicas: 3
selector:
matchLabels:
app: laravel-app
template:
metadata:
labels:
app: laravel-app
spec:
containers:
- name: laravel-app
image: your-registry/laravel-app:latest
ports:
- containerPort: 9000
envFrom:
- configMapRef:
name: laravel-config
- secretRef:
name: laravel-secret
volumeMounts:
- name: storage
mountPath: /var/www/html/storage
volumes:
- name: storage
persistentVolumeClaim:
claimName: laravel-storage
---
# kubernetes/service.yaml
apiVersion: v1
kind: Service
metadata:
name: laravel-app
spec:
selector:
app: laravel-app
ports:
- port: 9000
targetPort: 9000
type: ClusterIP
---
# kubernetes/ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: laravel-app
annotations:
kubernetes.io/ingress.class: nginx
cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
tls:
- hosts:
- example.com
secretName: laravel-tls
rules:
- host: example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: laravel-app
port:
number: 9000

7. Laravel 在微服务架构中的应用

Laravel 12 可以在微服务架构中发挥重要作用,是构建企业级微服务生态系统的专业解决方案。作为现代 PHP 微服务的技术栈选择,Laravel 提供了高性能服务器、API 网关、服务间通信和分布式事务等企业级特性,支持从单体应用向微服务架构的平滑过渡。

7.1 Laravel Octane

Octane 提供了高性能的应用服务器,基于 Swoole 或 RoadRunner,是 Laravel 12 中构建高性能微服务的核心组件。作为企业级微服务的运行时环境,Octane 提供了协程支持、内存常驻、连接池管理和异步任务等高级特性,显著提高 Laravel 应用的性能和并发处理能力。

安装与配置

1
2
3
4
5
6
7
composer require laravel/octane

# 安装 Swoole
pecl install swoole

# 或安装 RoadRunner
./vendor/bin/rr get

高级配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// config/octane.php
return [
'engine' => env('OCTANE_ENGINE', 'swoole'),
'listen' => env('OCTANE_LISTEN', '127.0.0.1:8000'),
'workers' => env('OCTANE_WORKERS', 4),
'task_workers' => env('OCTANE_TASK_WORKERS', 4),
'max_requests' => env('OCTANE_MAX_REQUESTS', 1000),
'timeout' => env('OCTANE_TIMEOUT', 60),
'grace_period' => env('OCTANE_GRACE_PERIOD', 120),
'queue_concurrency' => env('OCTANE_QUEUE_CONCURRENCY', 10),
'cache' => [
'store' => env('OCTANE_CACHE_STORE', null),
],
'tls' => [
'enabled' => env('OCTANE_TLS_ENABLED', false),
'cert' => env('OCTANE_TLS_CERT', ''),
'key' => env('OCTANE_TLS_KEY', ''),
],
];

企业级使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 1. 启动 Octane 服务器
php artisan octane:start --workers=8 --task-workers=4 --max-requests=5000

# 2. 热重载
php artisan octane:reload

# 3. 停止服务器
php artisan octane:stop

# 4. 监控状态
php artisan octane:status

# 5. 性能优化
# 配置 OPcache
# php.ini
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.validate_timestamps=0

性能对比

场景传统 PHP-FPMLaravel Octane (Swoole)性能提升
简单请求500 QPS8000 QPS16x
复杂请求200 QPS3000 QPS15x
内存使用100MB/进程60MB/进程40% 减少
启动时间200ms50ms75% 减少

7.2 API 网关构建

使用 Laravel 构建 API 网关,统一管理微服务的请求路由和认证。作为微服务架构的入口点,API 网关提供了请求路由、认证授权、流量控制、日志记录和服务发现等企业级特性,是构建安全、可扩展微服务架构的关键组件。

高级架构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│ 客户端 │ → → │ API 网关 │ → → │ 微服务 A │
└─────────────┘ └─────────────┘ └─────────────┘
↑ ↑ ↑ ↑
│ │ │ │
↓ ↓ ↓ ↓
┌─────────────┐ ┌─────────────┐
│ 服务发现 │ │ 微服务 B │
└─────────────┘ └─────────────┘
↑ ↑ ↑ ↑
│ │ │ │
↓ ↓ ↓ ↓
┌─────────────┐ ┌─────────────┐
│ 配置中心 │ │ 微服务 C │
└─────────────┘ └─────────────┘

企业级实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// 1. 服务发现集成
// config/services.php
return [
'user-service' => [
'url' => env('USER_SERVICE_URL', 'http://user-service:8000'),
'discovery' => true,
'health_check' => true,
],
'product-service' => [
'url' => env('PRODUCT_SERVICE_URL', 'http://product-service:8000'),
'discovery' => true,
'health_check' => true,
],
];

// 2. 高级 API 网关控制器
class ApiGatewayController extends Controller
{
public function proxy(Request $request)
{
$service = $request->route()->defaults('service');
$path = $request->path();
$method = $request->method();
$data = $request->all();

// 服务发现
$serviceUrl = $this->discoverService($service);

// 认证处理
$headers = $this->processAuthentication($request);

// 流量控制
$this->rateLimit($request, $service);

// 日志记录
$this->logRequest($request, $service);

// 代理请求
$response = Http::withHeaders($headers)
->timeout(30)
->retry(3, 1000)
->{$method}($serviceUrl . '/' . $path, $data);

// 响应处理
$this->logResponse($response, $service);

return response($response->body(), $response->status())
->withHeaders($response->headers()->all());
}

protected function discoverService($service)
{
// 实现服务发现逻辑
// 可以集成 Consul、etcd 等
return config("services.{$service}.url");
}

protected function processAuthentication($request)
{
// 实现认证处理逻辑
return [
'Authorization' => $request->header('Authorization'),
'X-User-ID' => $request->user()?->id,
];
}

protected function rateLimit($request, $service)
{
// 实现流量控制逻辑
$key = "rate_limit:{$service}:{$request->ip()}";
$limit = 100; // 每分钟请求限制

if (Redis::exists($key) && Redis::get($key) >= $limit) {
abort(429, 'Too Many Requests');
}

Redis::incr($key);
Redis::expire($key, 60);
}

protected function logRequest($request, $service)
{
// 实现请求日志记录
Log::info('API Gateway Request', [
'service' => $service,
'path' => $request->path(),
'method' => $request->method(),
'ip' => $request->ip(),
'user_id' => $request->user()?->id,
]);
}

protected function logResponse($response, $service)
{
// 实现响应日志记录
Log::info('API Gateway Response', [
'service' => $service,
'status' => $response->status(),
'time' => $response->transferStats->getTransferTime(),
]);
}
}

// 3. 路由配置
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
// 用户服务
Route::prefix('users')->group(function () {
Route::get('/', [ApiGatewayController::class, 'proxy'])->defaults('service', 'user-service');
Route::get('/{id}', [ApiGatewayController::class, 'proxy'])->defaults('service', 'user-service');
Route::post('/', [ApiGatewayController::class, 'proxy'])->defaults('service', 'user-service');
Route::put('/{id}', [ApiGatewayController::class, 'proxy'])->defaults('service', 'user-service');
Route::delete('/{id}', [ApiGatewayController::class, 'proxy'])->defaults('service', 'user-service');
});

// 产品服务
Route::prefix('products')->group(function () {
Route::get('/', [ApiGatewayController::class, 'proxy'])->defaults('service', 'product-service');
Route::get('/{id}', [ApiGatewayController::class, 'proxy'])->defaults('service', 'product-service');
Route::post('/', [ApiGatewayController::class, 'proxy'])->defaults('service', 'product-service');
});
});

7.3 服务间通信

服务间通信是微服务架构的核心组件,Laravel 12 提供了多种服务间通信方案,包括同步 HTTP 调用、异步消息队列和高性能 gRPC 通信。作为企业级微服务架构的通信层,服务间通信需要考虑可靠性、性能、安全性和可监控性等多个维度。

使用 Redis 实现异步通信

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// 1. 发布事件
use Illuminate\Support\Facades\Redis;

Redis::publish('user-created', json_encode([
'user_id' => $user->id,
'email' => $user->email,
'created_at' => $user->created_at->toISOString(),
]));

// 2. 订阅事件
// 创建订阅服务
// app/Console/Commands/SubscribeEvents.php
class SubscribeEvents extends Command
{
protected $signature = 'events:subscribe';
protected $description = 'Subscribe to Redis events';

public function handle()
{
Redis::subscribe(['user-created', 'order-placed'], function ($message) {
$data = json_decode($message, true);

// 处理事件
if (isset($data['user_id'])) {
$this->handleUserCreated($data);
} elseif (isset($data['order_id'])) {
$this->handleOrderPlaced($data);
}
});
}

protected function handleUserCreated($data)
{
// 处理用户创建事件
Log::info('User created event', $data);

// 发送欢迎邮件
Mail::to($data['email'])->send(new WelcomeEmail($data));
}

protected function handleOrderPlaced($data)
{
// 处理订单创建事件
Log::info('Order placed event', $data);
}
}

// 3. 启动订阅服务
php artisan events:subscribe

使用 gRPC 实现高性能通信

1
2
composer require spiral/roadrunner-grpc
composer require google/protobuf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// proto/user.proto
syntax = "proto3";

package user;

service UserService {
rpc GetUser(GetUserRequest) returns (GetUserResponse);
rpc CreateUser(CreateUserRequest) returns (CreateUserResponse);
rpc ListUsers(ListUsersRequest) returns (ListUsersResponse);
rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse);
rpc DeleteUser(DeleteUserRequest) returns (DeleteUserResponse);
}

message GetUserRequest {
int32 id = 1;
}

message GetUserResponse {
int32 id = 1;
string name = 2;
string email = 3;
bool active = 4;
string created_at = 5;
}

message CreateUserRequest {
string name = 1;
string email = 2;
string password = 3;
}

message CreateUserResponse {
int32 id = 1;
string name = 2;
string email = 3;
}

message ListUsersRequest {
int32 page = 1;
int32 per_page = 2;
string sort_by = 3;
string sort_order = 4;
}

message ListUsersResponse {
repeated User users = 1;
int32 total = 2;
int32 page = 3;
int32 per_page = 4;
}

message User {
int32 id = 1;
string name = 2;
string email = 3;
bool active = 4;
string created_at = 5;
}

message UpdateUserRequest {
int32 id = 1;
string name = 2;
string email = 3;
bool active = 4;
}

message UpdateUserResponse {
int32 id = 1;
string name = 2;
string email = 3;
bool active = 4;
}

message DeleteUserRequest {
int32 id = 1;
}

message DeleteUserResponse {
bool success = 1;
string message = 2;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// 生成 gRPC 代码
./vendor/bin/rr grpc:generate proto/user.proto

// 实现 gRPC 服务
// app/Grpc/UserService.php
class UserService implements \User\UserServiceInterface
{
public function GetUser(\User\GetUserRequest $request): \User\GetUserResponse
{
$user = User::find($request->getId());

if (!$user) {
throw new \Grpc\StatusException('User not found', \Grpc\STATUS_NOT_FOUND);
}

$response = new \User\GetUserResponse();
$response->setId($user->id);
$response->setName($user->name);
$response->setEmail($user->email);
$response->setActive($user->active);
$response->setCreatedAt($user->created_at->toISOString());

return $response;
}

public function CreateUser(\User\CreateUserRequest $request): \User\CreateUserResponse
{
$user = User::create([
'name' => $request->getName(),
'email' => $request->getEmail(),
'password' => bcrypt($request->getPassword()),
]);

$response = new \User\CreateUserResponse();
$response->setId($user->id);
$response->setName($user->name);
$response->setEmail($user->email);

return $response;
}

// 实现其他方法...
}

// 配置 gRPC 服务器
// config/grpc.php
return [
'services' => [
'user' => [
'class' => \App\Grpc\UserService::class,
'port' => 9000,
],
],
];

// 启动 gRPC 服务器
php artisan grpc:serve

7.4 微服务拆分策略

微服务拆分是构建成功微服务架构的关键,Laravel 12 提供了多种微服务拆分策略,包括按业务域拆分、按功能拆分和按技术边界拆分。作为企业级微服务架构的设计原则,微服务拆分需要考虑服务边界、数据一致性、通信成本和团队结构等多个因素。

企业级拆分策略

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 1. 按业务域拆分
// 用户服务
// 产品服务
// 订单服务
// 支付服务

// 2. 服务配置
// .env.user-service
APP_NAME=User Service
APP_KEY=
APP_DEBUG=false
APP_URL=http://user-service

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=user_service
DB_USERNAME=root
DB_PASSWORD=password

// 3. 数据迁移
// 创建服务特定迁移
php artisan make:migration create_users_table --path=database/migrations/user-service

// 4. 服务启动
// docker-compose.yml
services:
user-service:
build: ./services/user
ports:
- "8001:8000"
environment:
- APP_ENV=production
depends_on:
- mysql

product-service:
build: ./services/product
ports:
- "8002:8000"
environment:
- APP_ENV=production
depends_on:
- mysql

8. 自定义扩展包开发

Laravel 12 提供了创建自定义扩展包的完整工具链,是企业级功能封装和共享的专业解决方案。作为 Laravel 生态系统的重要组成部分,自定义扩展包开发涵盖了服务提供者设计、配置管理、资源发布和测试策略等多个维度,为专业开发者提供标准化、可复用的代码封装方案。

8.1 企业级扩展包结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
your-package/
├── src/ # 源代码目录
│ ├── YourPackageServiceProvider.php # 服务提供者
│ ├── Commands/ # Artisan 命令
│ ├── Http/ # HTTP 相关代码
│ │ ├── Controllers/ # 控制器
│ │ ├── Middleware/ # 中间件
│ │ └── Requests/ # 请求验证
│ ├── Models/ # 数据模型
│ ├── Traits/ # 特性
│ ├── Services/ # 业务逻辑服务
│ ├── Events/ # 事件
│ ├── Listeners/ # 事件监听器
│ ├── Jobs/ # 队列任务
│ └── ... # 其他目录
├── config/ # 配置文件
├── resources/ # 资源文件
│ ├── views/ # 视图
│ ├── lang/ # 语言文件
│ ├── assets/ # 静态资源
│ │ ├── css/ # CSS 文件
│ │ └── js/ # JavaScript 文件
│ └── ... # 其他资源
├── database/ # 数据库相关
│ ├── migrations/ # 迁移文件
│ ├── factories/ # 模型工厂
│ └── seeders/ # 数据填充
├── tests/ # 测试文件
│ ├── Feature/ # 功能测试
│ ├── Unit/ # 单元测试
│ └── TestCase.php # 测试基类
├── routes/ # 路由文件
│ ├── web.php # Web 路由
│ └── api.php # API 路由
├── docs/ # 文档目录
├── README.md # 文档
├── CHANGELOG.md # 变更日志
├── LICENSE # 许可证
├── composer.json # Composer 配置
├── phpunit.xml.dist # PHPUnit 配置
├── .github/ # GitHub 配置
│ ├── workflows/ # GitHub Actions
│ └── ISSUE_TEMPLATE/ # Issue 模板
└── .gitignore # Git 忽略文件

8.2 高级服务提供者设计

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php

namespace YourVendor\YourPackage;

use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Support\DeferrableProvider;

class YourPackageServiceProvider extends ServiceProvider implements DeferrableProvider
{
/**
* 注册服务
*/
public function register()
{
// 合并配置
$this->mergeConfigFrom(
__DIR__.'/../config/yourpackage.php', 'yourpackage'
);

// 绑定服务到容器
$this->app->singleton('yourpackage', function ($app) {
return new YourPackage(
$app->config->get('yourpackage'),
$app->make('cache'),
$app->make('log')
);
});

// 绑定门面
$this->app->alias('yourpackage', YourPackage::class);

// 注册命令
$this->registerCommands();
}

/**
* 引导服务
*/
public function boot()
{
// 发布配置
$this->publishes([
__DIR__.'/../config/yourpackage.php' => config_path('yourpackage.php'),
], 'yourpackage-config');

// 发布资源
$this->publishes([
__DIR__.'/../resources/views' => resource_path('views/vendor/yourpackage'),
], 'yourpackage-views');

$this->publishes([
__DIR__.'/../resources/lang' => resource_path('lang/vendor/yourpackage'),
], 'yourpackage-lang');

$this->publishes([
__DIR__.'/../resources/assets' => public_path('vendor/yourpackage'),
], 'yourpackage-assets');

// 发布迁移
if ($this->app->runningInConsole()) {
$this->loadMigrationsFrom(__DIR__.'/../database/migrations');
}

// 加载路由
$this->loadRoutesFrom(__DIR__.'/../routes/web.php');
$this->loadRoutesFrom(__DIR__.'/../routes/api.php');

// 加载视图
$this->loadViewsFrom(__DIR__.'/../resources/views', 'yourpackage');

// 加载语言文件
$this->loadTranslationsFrom(__DIR__.'/../resources/lang', 'yourpackage');

// 注册事件监听器
$this->registerEventListeners();

// 注册中间件
$this->registerMiddleware();
}

/**
* 注册命令
*/
protected function registerCommands()
{
if ($this->app->runningInConsole()) {
$this->commands([
Commands\InstallCommand::class,
Commands\PublishCommand::class,
Commands\SyncCommand::class,
]);
}
}

/**
* 注册事件监听器
*/
protected function registerEventListeners()
{
$this->app->events->listen(
'YourVendor\YourPackage\Events\SomethingHappened',
'YourVendor\YourPackage\Listeners\HandleSomethingHappened'
);
}

/**
* 注册中间件
*/
protected function registerMiddleware()
{
$this->app['router']->aliasMiddleware('yourpackage', Http\Middleware\YourPackageMiddleware::class);
}

/**
* 获取服务提供者提供的服务
*/
public function provides()
{
return [
'yourpackage',
YourPackage::class,
];
}
}

8.3 企业级测试策略

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php

namespace YourVendor\YourPackage\Tests;

use YourVendor\YourPackage\YourPackageServiceProvider;
use Orchestra\Testbench\TestCase as Orchestra;

abstract class TestCase extends Orchestra
{
/**
* 加载服务提供者
*/
protected function getPackageProviders($app)
{
return [
YourPackageServiceProvider::class,
];
}

/**
* 加载门面
*/
protected function getPackageAliases($app)
{
return [
'YourPackage' => \YourVendor\YourPackage\Facades\YourPackage::class,
];
}

/**
* 设置应用配置
*/
protected function defineEnvironment($app)
{
// 配置数据库
$app['config']->set('database.default', 'testing');
$app['config']->set('database.connections.testing', [
'driver' => 'sqlite',
'database' => ':memory:',
]);

// 配置缓存
$app['config']->set('cache.default', 'array');

// 配置包
$app['config']->set('yourpackage', [
'key' => 'test-key',
'secret' => 'test-secret',
'enabled' => true,
'debug' => true,
]);
}

/**
* 设置应用路由
*/
protected function defineRoutes($router)
{
$router->group(['middleware' => 'web'], function ($router) {
require __DIR__.'/../routes/web.php';
});

$router->group(['middleware' => 'api'], function ($router) {
require __DIR__.'/../routes/api.php';
});
}

/**
* 测试前准备
*/
protected function setUp(): void
{
parent::setUp();

// 运行迁移
$this->loadMigrationsFrom(__DIR__.'/../database/migrations');

// 填充测试数据
$this->artisan('db:seed', ['--class' => 'YourVendor\YourPackage\Database\Seeders\TestSeeder']);
}
}

// 功能测试示例
class YourPackageTest extends TestCase
{
public function testPackageCanBeAccessed()
{
$this->assertInstanceOf(
\YourVendor\YourPackage\YourPackage::class,
$this->app->make('yourpackage')
);
}

public function testConfigurationIsLoaded()
{
$this->assertEquals('test-key', config('yourpackage.key'));
}

public function testCommandWorks()
{
$this->artisan('yourpackage:install')
->assertExitCode(0);
}

public function testApiRouteWorks()
{
$response = $this->get('/api/yourpackage/test');
$response->assertStatus(200);
$response->assertJson(['message' => 'Test successful']);
}
}

8.4 扩展包发布与维护

企业级发布策略

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 1. 版本控制
# 遵循语义化版本规范 (SemVer)
# 主版本.次版本.修订版本
# 1.0.0

# 2. 文档管理
# README.md 详细文档
# API 文档生成
composer require --dev phpdocumentor/phpdocumentor
vendor/bin/phpdoc

# 3. 测试覆盖率
# 配置 PHPUnit
# .github/workflows/tests.yml
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
php: [8.1, 8.2, 8.3]
laravel: [10.*, 11.*, 12.*]
steps:
- uses: actions/checkout@v3
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
- name: Install dependencies
run: composer require laravel/framework:${{ matrix.laravel }}
- name: Run tests
run: vendor/bin/phpunit

# 4. 变更日志管理
# CHANGELOG.md
# 遵循 Keep a Changelog 规范

# 5. 发布到 Packagist
# 注册 Packagist 账号
# https://packagist.org

# 6. 维护策略
# 定期更新依赖
composer update

# 运行安全检查
composer audit

# 响应 GitHub Issues
# 提供技术支持

# 7. 兼容性测试
# 测试不同 Laravel 版本
# 测试不同 PHP 版本

企业级最佳实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// 1. 命名空间规范
// composer.json
{
"name": "your-vendor/your-package",
"description": "A Laravel package for doing amazing things",
"type": "library",
"version": "1.0.0",
"keywords": [
"laravel",
"package",
"your-package"
],
"homepage": "https://github.com/your-vendor/your-package",
"license": "MIT",
"authors": [
{
"name": "Your Name",
"email": "your@example.com",
"role": "Developer"
}
],
"require": {
"php": "^8.1",
"illuminate/support": "^10.0|^11.0|^12.0"
},
"require-dev": {
"orchestra/testbench": "^8.0|^9.0|^10.0",
"phpunit/phpunit": "^9.5|^10.0"
},
"autoload": {
"psr-4": {
"YourVendor\\YourPackage\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"YourVendor\\YourPackage\\Tests\\": "tests/"
}
},
"extra": {
"laravel": {
"providers": [
"YourVendor\\YourPackage\\YourPackageServiceProvider"
],
"aliases": {
"YourPackage": "YourVendor\\YourPackage\\Facades\\YourPackage"
}
}
},
"config": {
"sort-packages": true
},
"minimum-stability": "dev",
"prefer-stable": true
}

// 2. 门面实现
// src/Facades/YourPackage.php
namespace YourVendor\YourPackage\Facades;

use Illuminate\Support\Facades\Facade;

class YourPackage extends Facade
{
protected static function getFacadeAccessor()
{
return 'yourpackage';
}
}

// 3. 异常处理
// src/Exceptions/YourPackageException.php
namespace YourVendor\YourPackage\Exceptions;

use Exception;

class YourPackageException extends Exception
{
// 异常实现
}

// 4. 日志记录
// src/Services/YourService.php
namespace YourVendor\YourPackage\Services;

use Illuminate\Support\Facades\Log;

class YourService
{
public function doSomething()
{
try {
// 业务逻辑
} catch (\Exception $e) {
Log::error('YourPackage error', [
'message' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);

throw new \YourVendor\YourPackage\Exceptions\YourPackageException(
'An error occurred while doing something',
500,
$e
);
}
}
}

9. Laravel 生态系统最佳实践

9.1 扩展包选择策略

  • 官方包优先:优先使用 Laravel 官方维护的扩展包
  • 社区活跃度:选择 GitHub 星数多、维护活跃的包
  • 兼容性:确保包与当前 Laravel 版本兼容
  • 安全性:检查包的安全历史和漏洞报告
  • 性能影响:评估包对应用性能的影响
  • 长期维护:选择有长期维护计划的包

9.2 生态系统集成架构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
┌─────────────────────┐
│ Laravel 核心应用 │
├─────────────────────┤
│ 官方扩展包 │
│ ├── Sanctum/Passport│
│ ├── Horizon/Telescope│
│ └── Octane │
├─────────────────────┤
│ 社区扩展包 │
│ ├── Spatie 系列 │
│ ├── 第三方集成 │
│ └── 自定义包 │
├─────────────────────┤
│ 前端生态 │
│ ├── Livewire │
│ ├── Inertia.js │
│ └── 现代前端框架 │
├─────────────────────┤
│ 开发工具 │
│ ├── Sail/Valet │
│ ├── IDE 助手 │
│ └── 调试工具 │
└─────────────────────┘

9.3 性能优化策略

  1. 按需加载:只加载必要的扩展包
  2. 配置缓存:使用 php artisan config:cache 缓存配置
  3. 路由缓存:使用 php artisan route:cache 缓存路由
  4. 扩展包优化:移除未使用的扩展包,定期更新依赖
  5. 资源优化:合理使用前端资源,避免过度加载

9.4 安全性最佳实践

  1. 依赖扫描:定期使用 composer audit 扫描安全漏洞
  2. 版本锁定:在生产环境中锁定依赖版本
  3. 权限控制:严格控制扩展包的文件权限
  4. 代码审查:审查第三方扩展包的代码,特别是处理敏感数据的部分
  5. 安全更新:及时应用安全补丁和更新

10. 未来发展趋势

10.1 Laravel 生态系统的演进

  • 更多官方包:Laravel 团队将继续发布和维护高质量的官方扩展包
  • 更好的前端集成:进一步优化与现代前端框架的集成
  • 云原生支持:增强与云服务的集成,提供更好的云原生体验
  • AI 集成:将 AI 能力融入更多生态系统组件
  • 微服务工具链:提供更完整的微服务开发工具链

10.2 社区驱动的创新

  • 更多专业领域包:针对特定行业和领域的专业扩展包
  • 更好的开发者工具:提高开发效率的工具和服务
  • 跨框架兼容性:增强与其他 PHP 框架的互操作性
  • 标准化:推动 Laravel 扩展包开发的最佳实践和标准

总结

Laravel 12 的生态系统是一个完整、成熟的技术栈,从官方扩展包到社区贡献,从前端集成到微服务架构,为开发者提供了全面的工具集。通过合理利用这些工具和组件,开发者可以构建高质量、高性能、可维护的应用程序。

在构建 Laravel 应用时,应根据具体需求选择合适的生态系统组件,遵循最佳实践,并持续关注生态系统的发展趋势,以保持技术栈的先进性和竞争力。

通过深入理解和掌握 Laravel 生态系统,开发者可以显著提高开发效率,降低维护成本,构建更加可靠和创新的应用程序。