번역
App::bind 와 App::singleton의 차이점
Matt.park
2020. 6. 24. 11:52
원문 : stackoverflow.com/questions/25229064/laravel-difference-appbind-and-appsingleton
Laravel: Difference App::bind and App::singleton
I get a bit confused over all the nice things laravel has to offer in terms of the IOC container and facades. Since I'm not an experienced programmer it gets overwhelming to learn. I was wondering...
stackoverflow.com
require __DIR__ . '/vendor/autoload.php';
class FirstClass
{
public $value;
}
class SecondClass
{
public $value;
}
// Test bind()
$container = new Illuminate\Container\Container();
$container->bind('FirstClass');
$instance = $container->make('FirstClass');
$instance->value = 'test';
$instance2 = $container->make('FirstClass');
$instance2->value = 'test2';
echo "Bind: $instance->value vs. $instance2->value\n";
// Test singleton()
$container->singleton('SecondClass');
$instance = $container->make('SecondClass');
$instance->value = 'test';
$instance2 = $container->make('SecondClass');
$instance2->value = 'test2'; // <--- also changes $instance->value
echo "Singleton: $instance->value vs. $instance2->value\n";
결과는 아래와 같습니다.
// Bind 테스트
Bind: test vs. test2
// Singleton 테스트
Singleton: test2 vs. test2
All the magic lies in the Container::make method.
Container::make 메소드에 따라 결과가 다릅니다.처리됩니다.
If the binding is registered as shared (which means as singleton), the class instance is returned, otherwise a new instance every time.
App::bind로 사용하면 매번 새 인스턴스가 반환이 되고, App::singleton으로 사용하면 마지막에 생성한 클래스로 인스턴스가 반환 됩니다.
혹시, 원문과 다른 의미로 번역했다면, 알려주시길 부탁 드립니다.