🔹 เกริ่นนำ
Service Container ใน Laravel เป็นระบบ Dependency Injection อันทรงพลัง ที่ช่วยให้คุณจัดการ class และ dependency ต่าง ๆ ได้อย่างยืดหยุ่น สามารถผูก interface กับ class, สร้าง instance ใหม่ หรือแชร์ instance เดิมได้อย่างง่ายดาย
บทนี้จะแนะนำพื้นฐานการใช้งาน Service Container เพื่อจัดการกับ dependency และส่งต่อ object ไปยัง class หรือ controller อัตโนมัติ
🔸 การ Bind Service เข้าสู่ Container
use Illuminate\Support\Facades\App;
App::bind('App\Contracts\ReportService', 'App\Services\MonthlyReportService');
หรือ
$this->app->bind(...); // ใน ServiceProvider
🔸 การใช้ Singleton
$this->app->singleton('App\Services\Logger', function ($app) {
return new Logger('/logs/app.log');
});
🔸 การ resolve class ด้วย container
$logger = app()->make('App\Services\Logger');
🔸 การ Inject class เข้าสู่ Controller
public function __construct(ReportService $reportService)
{
$this->reportService = $reportService;
}
Laravel จะ resolve ReportService
ให้โดยอัตโนมัติจาก container
🔸 Binding ด้วย Interface
$this->app->bind(ReportServiceInterface::class, MonthlyReportService::class);
เมื่อใดก็ตามที่ Laravel เจอ ReportServiceInterface
จะสร้าง MonthlyReportService
ให้
💡 Service Container ทำให้โค้ดของคุณแยก concerns และทดสอบง่ายขึ้น