Laravel ရဲ့ Service Container ဟာ dependency injection နဲ့ dependency management ကို လုပ်ဆောင်ပေးတဲ့ အရေးကြီးတဲ့ feature တစ်ခုဖြစ်ပါတယ်။ ဒါကို code နမူနာတွေနဲ့ ရှင်းပြပေးပါမယ်။
- Binding:
Service Container မှာ class တွေကို bind လုပ်နိုင်ပါတယ်။
use App\Services\PaymentGateway;
use App\Services\StripePaymentGateway;
$this->app->bind(PaymentGateway::class, StripePaymentGateway::class);
- Resolving:
Bind လုပ်ထားတဲ့ class ကို resolve လုပ်နိုင်ပါတယ်။
$paymentGateway = $this->app->make(PaymentGateway::class);
- Singleton:
တစ်ခါဘဲ instantiate လုပ်စေချင်ရင် singleton ကိုသုံးနိုင်ပါတယ်။
$this->app->singleton(PaymentGateway::class, StripePaymentGateway::class);
- Constructor Injection:
Controller တွေမှာ dependency injection ကို အလိုအလျောက်လုပ်ပေးပါတယ်။
class PaymentController extends Controller
{
public function __construct(PaymentGateway $paymentGateway)
{
$this->paymentGateway = $paymentGateway;
}
}
- Method Injection:
Method တွေမှာလည်း dependency injection လုပ်နိုင်ပါတယ်။
public function store(Request $request, PaymentGateway $paymentGateway)
{
// Use $paymentGateway
}
- Service Providers:
Service providers တွေမှာ bindings တွေကို register လုပ်လေ့ရှိပါတယ်။
class PaymentServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind(PaymentGateway::class, StripePaymentGateway::class);
}
}
Service Container က Laravel application ရဲ့ အဓိက အစိတ်အပိုင်းတစ်ခုဖြစ်ပြီး၊ loose coupling နဲ့ testable code ရေးသားဖို့ အထောက်အကူပြုပါတယ်။