Laravel : Difference App :: bind 및 App :: singleton
나는 laravel이 IOC 컨테이너 및 파사드 측면에서 제공해야하는 모든 멋진 것들에 대해 약간 혼란스러워합니다. 나는 경험 많은 프로그래머가 아니기 때문에 배우는 것이 압도적입니다.
이 두 가지 예의 차이점이 무엇인지 궁금합니다.
'Foo'에 대한 파사드이며 다음을 통해 컨테이너에 등록됩니다.
App::bind()
'Foo'에 대한 파사드이며 다음을 통해 컨테이너에 등록됩니다.
App::singleton()
첫 번째 예에서는 클래스 의 여러 인스턴스 가 생성되고 두 번째 예에서는를 통해 바인딩되므로 해당 개체의 메서드가 호출 될 때마다 동일한 인스턴스 가 반환 되므로 가장 잘 이해 Foo::method()
하면 다시 작성됩니다 .$app->make['foo']->method()
Foo
App::singleton()
Foo
이 질문에 대한 답이 분명하다면 미안하지만이 문제에 대한 확인을 찾을 수 없으며 명확하게 설명되어 있지 않습니다.
똑같습니다.
아주 간단한 증거는 bevahior를 테스트하는 것입니다. 라 라벨 애플리케이션은 단순히를 확장하기 때문에 Illuminate\Container\Container
컨테이너 만 사용 하여 테스트 할 것입니다 (제 경우에는 컨테이너를 composer.json에 대한 종속성으로 만 추가했습니다).
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: test vs. test2
Singleton: test2 vs. test2
더러운 증거 일 수 있지만 실제로는 하나입니다.
모든 마법은 Container::make
방법에 있습니다. 바인딩이 공유 (단일 톤)로 등록 된 경우 클래스 인스턴스가 반환되고 그렇지 않으면 매번 새 인스턴스가 반환됩니다.
출처 : https://github.com/laravel/framework/blob/4.2/src/Illuminate/Container/Container.php#L442
BTW 는 세 번째 매개 변수가 true로 설정된 Container::singleton
것과 동일 Container::bind
합니다.
파사드는 기본 바인딩이 싱글 톤이 아니더라도 싱글 톤으로 작동합니다.
다음이 있다고 가정 해 보겠습니다.
$app->bind('foo', 'FooConcrete'); // not a singleton
과:
class Foo extends \Illuminate\Support\Facades\Facade {
protected static function getFacadeAccessor() { return 'foo'; }
}
Then this will create 2 instances of FooConcrete
, as usual:
app('foo');
app('foo');
But this will create only one instance of FooConcrete
and reuse it:
Foo::someMethod();
Foo::someMethod();
It is because resolveFacadeInstance()
stores the resolved instances.
There is an exception though. Most of the time the defined getFacadeAccessor()
returns a string, as shown above, but it can also return an object. Example from the Schema
Facade:
protected static function getFacadeAccessor() {
return static::$app['db']->connection()->getSchemaBuilder();
}
In such a case, resolveFacadeInstance()
doesn't store the instance.
So if getFacadeAccessor()
returns a new instance, each call to the Facade creates a new instance as well.
But somewhere I read that Laravel treats classes called via facades always as singletons?
Thereby, I encountered this problem:
I have a demo class normally bound via
$this->app->bind('demo', function() { return new Demo(); }
파사드 설정
protected static function getFacadeAccessor () {return 'demo'; }
수업 자체는 다음과 같습니다.
클래스 데모 { 개인 $ value1; 개인 $ value2; 공용 함수 setVal1 ($ value) { $ this-> value1 = $ value; } 공용 함수 setVal2 ($ value) { $ this-> value2 = $ value; } 공용 함수 getVals () { 반환 'Val 1 :'. $ this-> value1. '발 2 :'. $ this-> value2; } }
이 클래스에서 파사드를 사용하면 클래스의 객체를 인스턴스화 한 다음 해당 객체에서 메서드를 호출한다고 말씀하셨습니다.
엉덩이를 좀 더 테스트 한 결과이 매우 이상한 행동을 발견했습니다 (적어도 나에게는).
만약 내가한다면
데모 :: setVal1 ( '13654');과
데모 :: setVal2 ( 'random string')
I shouldn't be able to use Demo::getVals() to retrieve the values I just created, should I? Since every time a facade method is used a new object will be instantiated and how can one object retrieve properties of another object? There should be three different instances but still I'm able to retrieve the properties from those other instances...
참고URL : https://stackoverflow.com/questions/25229064/laravel-difference-appbind-and-appsingleton
'IT TIP' 카테고리의 다른 글
Javascript / jQuery를 사용하여 외부 스타일 시트에서 CSS 값 가져 오기 (0) | 2020.12.08 |
---|---|
UIEdgeInsetsMake는 어떻게 작동합니까? (0) | 2020.12.08 |
React Native 및 API 백엔드를 사용한 인증 (0) | 2020.12.08 |
이 iPhone 6은 iOS 10.1 (14B55c)을 실행 중이며이 버전의 Xcode에서 지원하지 않을 수 있습니다. (0) | 2020.12.08 |
SQL Server .bak 파일을 MySQL로 가져 오는 방법은 무엇입니까? (0) | 2020.12.08 |