Framework cung cấp sẵn router, ORM, template, xác thực, bảo mật để bạn tập trung vào nghiệp vụ. Bài này giới thiệu các framework PHP phổ biến, Composer, rồi làm quen Laravel qua một chức năng quản lý sinh viên: route, migration, model Eloquent, controller và view Blade.
- Hiểu lợi ích và chi phí khi dùng framework
- Dùng Composer để quản lý thư viện
- Tạo dự án Laravel, hiểu cấu trúc thư mục
- Viết route, migration, model, controller, view Blade cho một tài nguyên
- Composer
- Trình quản lý gói chuẩn của PHP.
- Artisan
- Công cụ dòng lệnh của Laravel.
- Eloquent
- ORM: mỗi bảng là một lớp Model.
- Blade
- Template engine của Laravel.
- Migration
- Tệp mô tả thay đổi cấu trúc CSDL, quản lý theo phiên bản.
Khái niệm và lý thuyết
| Framework | Đặc điểm | Phù hợp |
|---|---|---|
| Laravel | Phổ biến nhất, cú pháp biểu cảm, hệ sinh thái lớn (Eloquent, Blade, Sanctum, Livewire) | Hầu hết dự án mới |
| Symfony | Công nghiệp, nhiều thành phần (Doctrine, Twig), là lõi của Laravel và Drupal | Dự án lớn, lâu dài |
| CodeIgniter | Gọn nhẹ, ít quy ước, dễ học | Dự án nhỏ, hosting hạn chế |
| Slim | Micro-framework cho API | API nhỏ |
| CakePHP, Yii | Lâu đời, vẫn được bảo trì | Dự án kế thừa |
Lợi ích: năng suất cao, quy ước chung cho cả nhóm, bảo mật tích hợp (CSRF, XSS, SQL injection). Chi phí: thời gian học quy ước, phải biết đọc tài liệu khi lỗi, yêu cầu PHP mới và Composer.
Composer và tạo dự án Laravel
# Cài Composer tại getcomposer.org, kiểm tra:
composer --version
# Tạo dự án (cần PHP 8.2+)
composer create-project laravel/laravel qlsv-laravel
cd qlsv-laravel
php artisan serve # http://127.0.0.1:8000qlsv-laravel/
├── app/Http/Controllers/ # Controller
├── app/Models/ # Model Eloquent
├── database/migrations/ # Migration
├── resources/views/ # View Blade (.blade.php)
├── routes/web.php, api.php # Định tuyến
├── public/ # Thư mục công khai (index.php)
├── .env # Cấu hình: DB_DATABASE=qlsv, DB_USERNAME=rootVới XAMPP: sửa .env cho khớp MySQL (DB_DATABASE, DB_USERNAME=root, DB_PASSWORD rỗng), tạo CSDL trong phpMyAdmin rồi chạy php artisan migrate.
Migration và Model
php artisan make:model SinhVien -mcr # tạo Model + migration + controller resource<?php
// database/migrations/xxxx_create_sinh_viens_table.php
public function up(): void {
Schema::create('sinh_viens', function (Blueprint $table) {
$table->id();
$table->string('ma_sv', 10)->unique();
$table->string('ho_ten', 100);
$table->string('lop', 20);
$table->string('email')->nullable();
$table->date('ngay_sinh')->nullable();
$table->timestamps();
});
}
// app/Models/SinhVien.php
class SinhVien extends Model {
protected $fillable = ['ma_sv', 'ho_ten', 'lop', 'email', 'ngay_sinh'];
}php artisan migrate<?php
// Eloquent thay cho SQL tay (tự dùng prepared statement)
SinhVien::all();
SinhVien::where('lop', 'K66 Tin')->orderBy('ho_ten')->get();
SinhVien::where('ho_ten', 'like', "%An%")->paginate(10);
$sv = SinhVien::create(['ma_sv' => 'SV001', 'ho_ten' => 'Lò Văn An', 'lop' => 'K66 Tin']);
$sv->update(['lop' => 'K65 Tin']);
SinhVien::findOrFail(1)->delete();Route và Controller
<?php
// routes/web.php
use App\Http\Controllers\SinhVienController;
Route::resource('sinhvien', SinhVienController::class); // 7 route CRUD chuẩn
// app/Http/Controllers/SinhVienController.php
class SinhVienController extends Controller {
public function index() {
$ds = SinhVien::orderBy('ho_ten')->paginate(10);
return view('sinhvien.index', compact('ds'));
}
public function create() { return view('sinhvien.form'); }
public function store(Request $request) {
$d = $request->validate([
'ma_sv' => 'required|max:10|unique:sinh_viens',
'ho_ten' => 'required|min:3',
'lop' => 'required',
'email' => 'nullable|email',
]);
SinhVien::create($d);
return redirect()->route('sinhvien.index')->with('ok', 'Đã thêm sinh viên');
}
public function destroy(SinhVien $sinhvien) { // tự tìm theo id (route model binding)
$sinhvien->delete();
return back()->with('ok', 'Đã xóa');
}
}validate() tự chuyển về form kèm lỗi nếu dữ liệu sai; unique:sinh_viens kiểm tra trùng trong CSDL. Chạy php artisan route:list để xem 7 route được sinh.
View Blade
{{-- resources/views/layouts/app.blade.php --}}
<!DOCTYPE html><html lang="vi"><head><meta charset="UTF-8"><title>@yield('title', 'QLSV')</title></head>
<body>
<nav><a href="/{{ route('sinhvien.index') }}">Sinh viên</a> | <a href="/{{ route('sinhvien.create') }}">Thêm</a></nav>
@if (session('ok')) <p style="color:green">{{ session('ok') }}</p> @endif
@yield('content')
</body></html>
{{-- resources/views/sinhvien/index.blade.php --}}
@extends('layouts.app')
@section('title', 'Danh sách sinh viên')
@section('content')
<h1>Danh sách sinh viên</h1>
<table border="1">
@foreach ($ds as $sv)
<tr><td>{{ $sv->ma_sv }}</td><td>{{ $sv->ho_ten }}</td><td>{{ $sv->lop }}</td>
<td><form method="post" action="{{ route('sinhvien.destroy', $sv) }}">@csrf @method('DELETE')
<button onclick="return confirm('Xóa?')">Xóa</button></form></td></tr>
@endforeach
</table>
{{ $ds->links() }}
@endsection{{ }} tự mã hóa HTML (chống XSS); @csrf chèn token; @extends/@section kế thừa layout; $ds->links() sinh phân trang.
Học Laravel hiệu quả: làm lại đúng ứng dụng quản lý sinh viên đã viết bằng PHP thuần (loạt PHP và MySQL), bạn sẽ thấy framework thay bạn những gì. Tài liệu chính thức laravel.com/docs rất đầy đủ; Laracasts có video miễn phí.
Đừng học framework trước khi hiểu PHP thuần, HTTP, form, session và SQL: khi gặp lỗi bạn sẽ không biết framework đang làm gì bên dưới.
- Cài Composer, tạo dự án Laravel, chạy php artisan serve.
- Tạo migration, model, controller resource cho sinh viên và chạy migrate.
- Hoàn thiện index, create, store, destroy với view Blade.
- Thêm chức năng tìm kiếm theo tên và phân trang 10 dòng.
- Framework = router + ORM + template + bảo mật + quy ước.
- Composer quản lý thư viện; Artisan sinh mã, chạy migration.
- Eloquent thay SQL tay; validate() kiểm tra dữ liệu; Blade tự chống XSS.
- Nắm PHP thuần, MVC, SQL trước thì học Laravel rất nhanh.