Giao diện
Context
Giới thiệu (Introduction)
"Context" trong Laravel cho phép bạn capture, retrieve và share thông tin xuyên suốt requests, jobs, và commands trong ứng dụng. Thông tin context cũng được đính kèm vào logs, giúp bạn có cái nhìn sâu hơn về luồng thực thi code.
Cơ chế hoạt động (How it Works)
Mỗi request incoming, job, hoặc Artisan command tạo một "context" riêng. Thông tin trong context tự động truyền sang queued jobs — giúp job có đầy đủ ngữ cảnh từ request ban đầu.
Ghi nhận Context (Capturing Context)
Lưu thông tin vào context hiện tại bằng Context facade:
php
use Illuminate\Support\Facades\Context;
Context::add('key', 'value');
// Thêm nhiều items
Context::add([
'first_key' => 'value',
'second_key' => 'value',
]);Chỉ thêm nếu chưa có
php
Context::addIf('key', 'second');
// Nếu 'key' đã tồn tại → giữ giá trị cũTăng / Giảm giá trị
php
Context::increment('records_added');
Context::increment('records_added', 5);
Context::decrement('records_added');
Context::decrement('records_added', 5);Conditional Context
php
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Context;
Context::when(
Auth::user()->isAdmin(),
fn ($context) => $context->add('permissions', Auth::user()->permissions),
fn ($context) => $context->add('permissions', []),
);Scoped Context
Thêm context tạm thời, tự động rollback sau khi callback hoàn thành:
php
Context::scope('my-scope', function () {
Context::add('key', 'scoped-value');
// 'key' chỉ có 'scoped-value' trong scope này
});
// Sau scope, 'key' trở về giá trị cũ (hoặc bị xóa)Stacks
Context hỗ trợ "stacks" — danh sách giá trị theo thứ tự thêm vào:
php
use Illuminate\Support\Facades\Context;
Context::push('breadcrumbs', 'first_value');
Context::push('breadcrumbs', 'second_value', 'third_value');
Context::get('breadcrumbs');
// ['first_value', 'second_value', 'third_value']Truy xuất Context (Retrieving Context)
php
$value = Context::get('key');
// Lấy tất cả
$context = Context::all();
// Lấy và xóa
$value = Context::pull('key');Kiểm tra tồn tại
php
if (Context::has('key')) {
// ...
}
if (Context::hasHidden('key')) {
// ...
}Xóa Context (Removing Context)
php
Context::forget('key');
Context::forget(['first_key', 'second_key']);Hidden Context
Context "hidden" — dữ liệu không xuất hiện trong logs:
php
Context::addHidden('api_token', 'secret-token');
$value = Context::getHidden('api_token');
Context::forgetHidden('api_token');Events
Context dispatch hai events:
Dehydrating
Fired trước khi context được serialized (ví dụ: trước khi truyền sang queued job):
php
Context::dehydrating(function (Context $context) {
$context->addHidden('api_token', 'secret-for-job');
});Hydrated
Fired sau khi context được deserialized (ví dụ: khi job bắt đầu chạy):
php
Context::hydrated(function (Context $context) {
if ($context->hasHidden('api_token')) {
ApiService::setToken($context->getHidden('api_token'));
}
});