PHP 8.x hiện đại - Laravel Framework - API Development
<?php
declare(strict_types=1);
class User
{
// Typed properties (PHP 8.0+)
public int $id;
public string $name;
public ?string $email = null; // Nullable
// Union types (PHP 8.0+)
public int|float $balance;
// Constructor property promotion (PHP 8.0+)
public function __construct(
public readonly int $id, // readonly (PHP 8.1+)
public string $name,
public ?string $email = null
) {}
}
// Sử dụng
$user = new User(1, "Nguyen Van A", "[email protected]");
echo $user->name; // Nguyen Van A
<?php
use Attribute;
#[Attribute(Attribute::TARGET_PROPERTY)]
class Validate
{
public function __construct(
public string $rule,
public string $message = ''
) {}
}
class Product
{
#[Validate('required', 'Tên sản phẩm bắt buộc')]
public string $name;
#[Validate('min:0', 'Giá phải >= 0')]
public float $price;
}
// Đọc attribute bằng Reflection
$ref = new ReflectionClass(Product::class);
foreach ($ref->getProperties() as $prop) {
$attrs = $prop->getAttributes(Validate::class);
foreach ($attrs as $attr) {
$validate = $attr->newInstance();
echo "{$prop->getName()}: {$validate->rule}\n";
}
}
<?php
// Match expression (thay thế switch)
$status = 'pending';
$message = match($status) {
'pending' => 'Đang chờ xử lý',
'processing' => 'Đang xử lý',
'completed' => 'Hoàn thành',
'cancelled' => 'Đã hủy',
default => 'Không xác định'
};
// Named arguments
function createOrder(
string $product,
int $quantity = 1,
float $discount = 0,
bool $priority = false
) {
// ...
}
// Gọi với named arguments (dễ đọc hơn)
createOrder(
product: "Laptop",
quantity: 2,
priority: true // Bỏ qua discount
);
Laravel là PHP framework phổ biến nhất, cung cấp MVC architecture, Eloquent ORM, Blade templating, và nhiều tính năng enterprise-ready.
# Cài đặt Composer (nếu chưa có)
curl -sS https://getcomposer.org/installer | php
# Tạo project Laravel mới
composer create-project laravel/laravel my-app
# Hoặc dùng Laravel installer
composer global require laravel/installer
laravel new my-app
# Chạy development server
cd my-app
php artisan serve
# => http://127.0.0.1:8000
<?php
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Post extends Model
{
protected $fillable = ['title', 'content', 'user_id'];
// Relationships
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
// Scope (query builder helper)
public function scopePublished($query)
{
return $query->where('status', 'published');
}
}
// Sử dụng
$posts = Post::published()
->with(['user', 'comments']) // Eager loading
->orderBy('created_at', 'desc')
->paginate(10);
// Tạo mới
$post = Post::create([
'title' => 'Bài viết mới',
'content' => 'Nội dung...',
'user_id' => auth()->id()
]);
<?php
// app/Http/Controllers/Api/PostController.php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
class PostController extends Controller
{
public function index(): JsonResponse
{
$posts = Post::with('user')->latest()->paginate(15);
return response()->json([
'success' => true,
'data' => $posts
]);
}
public function store(Request $request): JsonResponse
{
$validated = $request->validate([
'title' => 'required|string|max:255',
'content' => 'required|string',
]);
$post = $request->user()->posts()->create($validated);
return response()->json([
'success' => true,
'data' => $post,
'message' => 'Tạo bài viết thành công'
], 201);
}
}
PHP-FIG (Framework Interop Group) định nghĩa các tiêu chuẩn:
• PSR-1/PSR-12: Coding style
• PSR-4: Autoloading
• PSR-7: HTTP message interfaces
• PSR-11: Container interface
# Cài đặt PHP CS Fixer
composer require --dev friendsofphp/php-cs-fixer
# Tạo config file .php-cs-fixer.php
# Chạy fix
./vendor/bin/php-cs-fixer fix src/
• PHP Official
Docs
• Laravel
Documentation
• Dịch vụ thiết kế Website - Không Gian AI