一、Laravel核心概念深入
1. 服务容器与依赖注入
(1) 绑定与解析
// 在服务提供者中注册绑定
$this->app->bind('PDFGenerator', function ($app) {
return new PDFGenerator(config('services.pdf'));
});
// 控制器中使用
public function __construct(PDFGenerator $pdf) {
$this->pdf = $pdf;
}
(2) 接口绑定实现
// 定义接口
interface PaymentGateway {
public function charge($amount);
}
// 实现类
class StripePayment implements PaymentGateway {
public function charge($amount) { /* ... */ }
}
// 绑定
$this->app->bind(PaymentGateway::class, StripePayment::class);
// 使用
public function pay(PaymentGateway $payment) {
$payment->charge(100);
}
2. 中间件高级用法
(1) 创建中间件
php artisan make:middleware CheckUserRole
// app/Http/Middleware/CheckUserRole.php
public function handle($request, Closure $next, $role) {
if (!auth()->check() || !auth()->user()->hasRole($role)) {
abort(403);
}
return $next($request);
}
(2) 注册并使用
// Kernel.php
protected $routeMiddleware = [
'role' => \App\Http\Middleware\CheckUserRole::class,
];
// 路由中使用
Route::group(['middleware' => 'role:admin'], function () {
Route::get('/admin', 'AdminController@dashboard');
});
二、队列与任务调度
1. 队列系统配置
(1) 配置.env
QUEUE_CONNECTION=database # 使用数据库队列
(2) 创建迁移
php artisan queue:table
php artisan migrate
2. 创建任务
php artisan make:job ProcessPodcast
// app/Jobs/ProcessPodcast.php
public function handle() {
// 处理耗时任务
$this->podcast->process();
}
3. 分发任务
ProcessPodcast::dispatch($podcast)
->onQueue('processing')
->delay(now()->addMinutes(10));
4. 运行队列处理器
php artisan queue:work --queue=high,default,low
5. 任务调度
// app/Console/Kernel.php
protected function schedule(Schedule $schedule) {
$schedule->job(new CleanUpOldRecords)
->daily()
->at('03:00');
$schedule->command('backup:run')
->weeklyOn(1, '2:00');
}
三、测试驱动开发(TDD)
1. PHPUnit基础
(1) 创建测试
php artisan make:test UserTest
(2) 测试示例
// tests/Feature/UserTest.php
public function test_user_can_register()
{
$response = $this->post('/register', [
'name' => 'Test User',
'email' => 'test@example.com',
'password' => 'password',
'password_confirmation' => 'password'
]);
$response->assertRedirect('/home');
$this->assertDatabaseHas('users', ['email' => 'test@example.com']);
}
2. 数据库测试
public function test_article_creation()
{
$user = User::factory()->create();
$article = Article::factory()->create([
'user_id' => $user->id
]);
$this->assertInstanceOf(Article::class, $article);
$this->assertEquals(1, $user->articles->count());
}
3. HTTP测试
public function test_api_returns_articles()
{
Article::factory()->count(3)->create();
$response = $this->getJson('/api/articles');
$response->assertStatus(200)
->assertJsonCount(3)
->assertJsonStructure([
'*' => ['id', 'title', 'content']
]);
}
四、性能优化技巧
1. 数据库优化
(1) 查询优化
// 避免N+1问题
$articles = Article::with('user', 'comments')->get();
// 只选择需要的列
User::select('id', 'name')->get();
(2) 索引优化
// 迁移中添加索引
$table->index('created_at');
$table->unique('email');
2. 缓存策略
(1) 路由缓存
php artisan route:cache
(2) 视图缓存
php artisan view:cache
(3) 数据缓存
$articles = Cache::remember('articles.all', 3600, function () {
return Article::with('user')->latest()->get();
});
3. 前端优化
(1) 混合编译
// webpack.mix.js
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.version();
(2) 懒加载
// 图片懒加载
<img src="placeholder.jpg" data-src="real-image.jpg" class="lazyload">
// 路由懒加载
const About = () => import('./views/About.vue');
五、项目实战:电商系统
1. 系统功能设计
- 用户中心
- 商品管理
- 购物车系统
- 订单流程
- 支付集成
- 评价系统
2. 数据库设计
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->decimal('price', 10, 2);
$table->integer('stock');
$table->timestamps();
});
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained();
$table->decimal('total', 10, 2);
$table->string('status')->default('pending');
$table->timestamps();
});
3. 支付流程实现
(1) 支付接口
interface PaymentGateway {
public function charge($amount, $token);
public function createCustomer($email);
}
class StripeGateway implements PaymentGateway {
// 实现方法
}
(2) 订单处理
public function processOrder(Request $request) {
$cart = Cart::getContent();
DB::transaction(function () use ($cart, $request) {
$order = Order::create([
'user_id' => auth()->id(),
'total' => $cart->getTotal()
]);
foreach ($cart as $item) {
$order->items()->create([
'product_id' => $item->id,
'quantity' => $item->quantity,
'price' => $item->price
]);
}
$this->payment->charge(
$order->total,
$request->payment_token
);
Cart::clear();
});
return redirect()->route('orders.show', $order);
}
六、项目部署与监控
1. 生产环境部署
(1) Forge部署流程
- 连接服务器
- 配置Nginx
- 设置部署脚本
- 配置环境变量
- 设置队列处理器
(2) 零停机部署
# 部署脚本示例
php artisan down
git pull origin master
composer install --no-dev
php artisan migrate --force
php artisan view:cache
php artisan route:cache
php artisan config:cache
php artisan up
2. 系统监控
(1) Horizon仪表板
composer require laravel/horizon
php artisan horizon:install
php artisan horizon
(2) 错误监控
// 报告异常
report(function (PaymentFailed $e) {
// 通知团队
});
七、作业练习
-
完成电商系统核心功能:
- 实现商品列表与详情页
- 开发购物车功能
- 完成订单创建流程
- 集成支付网关
-
添加后台管理系统:
- 商品CRUD操作
- 订单管理
- 数据统计仪表盘
-
实现API接口:
- 使用API资源
- 添加JWT认证
- 支持分页和过滤
-
编写测试用例:
- 测试购物车逻辑
- 测试订单流程
- 测试支付集成
八、学习路线建议
1. 进阶学习方向
- 前端整合:Vue/React与Laravel结合
- 微服务架构:Lumen与服务拆分
- DevOps:Docker与CI/CD流程
- 性能调优:数据库优化与缓存策略
2. 推荐资源
- Laravel官方文档
- Laracasts视频教程
- 《Laravel框架关键技术解析》
- GitHub优秀开源项目
课程总结
通过这十节课的学习,你已经从PHP零基础成长为能够:
- 理解PHP核心语法与面向对象编程
- 掌握MySQL数据库设计与操作
- 使用Laravel框架开发完整应用
- 实现前后端分离与API开发
- 进行测试驱动开发与性能优化
- 部署和维护生产环境应用
接下来建议选择一个实际项目进行实践,在解决问题中深化理解! 🎉
这一切,似未曾拥有