17/09/2023
Laravel ရဲ့ service container
Laravel ရဲ့ service container ဆိုတာ သူရဲ့အဆိုရတော့ zero configuration resolution ပေါ့ ဆိုလိုတာက dependencies မရှိတဲ့ class သို့မဟုတ် concrete class တွေဟာ ဘာမှပြောစရာမလိုပဲ သူ့ဟာသူ resolve လုပ်ပေးတာပေါ့ အောက်ပါcodeမှာဆို ဘာ dependency မှ မရှိတဲ့ connection.php ကို ConnectionController ရဲ့ construct method ကနေ Dependency Injection ခေါ်ထားပါတယ် အဲ့ဒီအခါ Connection.php ကို resolve လုပ်ပြီး instance ကိုပြန်ပေးပါတယ်
class Connection
{
public function connect()
{
return "connect to db”;
}
}
class ConnectorController extends Controller
{
public $connection;
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
}
ဒါဆို အောက်က code လို Connection.php မှာ dependency ရှိလာရင်ရော ဘယ်လို လုပ်မလည်း ?
class Connection
{
public $key;
public function __construct($key)
{
$this->key = $key;
}
public function connect()
{
// connect using $key
return "connect to db";
}
}
ဒါဆိုရင်တော့ ConnectionController ထဲမှာ resolve လုပ်ရမယ့် Connection.php မှာ unresolvable dependency ဖြစ်နေပါတယ်ဆိုပြီး exception throw ပါလိမ့်မယ် Laravel အနေနဲ့ သူလည်း Connection.php အတွက် ဘယ်လိုရှင်းရမလည်းဆိုတာ လိုနေပါပြီ အောက်က code အတိုင်း AppServiceProvider ရဲ့ register method ထဲမှာသွားပြီး instruction ရေးပေးရပါ့မယ်
public function register(): void
{
$this->app->bind(Connection::class, function () {
return new Connection("blahblah");
});
}
ဒါဟာဘယ်လိုလည်းဆိုတော့ Connection.php ကို Service Container နဲ့ bind လိုက်တာပါ resolve လုပ်ပေးဖို့လိုလာတိုင်း new Connection("blahblah"); ကို သုံးခိုင်းလိုက်တာပါ
နောက်တစ်ခုက Bind လိုက်တာဖြစ်တဲ့အတွက်
app()->make(Connection::class) ဆိုပြီး မည်သည့်နေရာကမဆို container ထဲကနေ ပြန်လည်ခေါ်ယူလို့ရသွားပါတယ်
Service Container ရဲ့နောက်ကွယ်က အလုပ်လုပ်ပုံကိုသိချင်ရင်တော့ vendor/laravel/framework/src/Illuminate/Contracts/Container/Container.php မှာကြည့်လို့ရပါတယ်
Service container နဲ့ decouple ဖြစ်တဲ့ code တွေကိုလည်း ရေးလို့ရပါသေးတယ် နောက်ကွယ်ကဘယ်လို resolve လုပ်တယ်ဆိုတာ ရိုးရှင်းလှတဲ့ container တစ်ခု ရေးကြည့်ကြပါမယ်
အဲ့အကြောင်းကိုတော့ နောက် post တစ်ခု သို့မဟုတ် အကြောင်းအရာများလို့ video နဲ့ဖြစ်ဖြစ် ရှင်းမှအဆင်ပြေမှာပါ
အားလုံးပဲ ဘဝရဲ့ dependency တွေ resolve နိုင်ကြပါစေဗျာ
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.