1
我閱讀了關於Service Container的文檔以及其他一些關於YouTube的信息,但仍不完全瞭解什麼是服務容器以及如何或何時使用它,所以如果您能簡單地解釋什麼是服務容器以及如何使用bind
, make
,resolving
等等什麼是Laravel服務容器?
我閱讀了關於Service Container的文檔以及其他一些關於YouTube的信息,但仍不完全瞭解什麼是服務容器以及如何或何時使用它,所以如果您能簡單地解釋什麼是服務容器以及如何使用bind
, make
,resolving
等等什麼是Laravel服務容器?
服務容器用於概念「控制反轉,IOC」 它基本上是在那裏你resolve
您的服務等
class SomethingInMyApplication {
public function __constructor(LoggerInterface $logger) {
$logger->info("hello world");
}
}
$container->bind(ILoggerInterface::class, MySpecialLogger::class);
$something = $container->make(SomethingInMyApplication::class);
你MySpecialLogger
實現該接口的容器,但你也可以綁定其他的東西來實現LoggerInterface::class
它可以變得更復雜與其他設計模式,如工廠等 所以綁定正確的記錄器實現基於配置。
在您的應用程序中,您可以使用DI LoggerInterface,因此您可以輕鬆地將使用的實現從MySpecialLogger
更改爲其他內容。
容器基本上檢查__constructor
中的所有參數,並嘗試從容器中解析這些類型。
$container->bind(ILoggerInterface::class, MySpecialLogger::class);
$container->make(SomethingInMyApplication::class);
// In the make method
$class = SomethingInMyApplication::class;
// Refelection to read all the arguments in the constructor we see the logger interface
$diInstance = $container->resolve(LoggerInterface::class);
$instance = new $class($diInstance);
// We created the SomethingInMyApplication
https://stackoverflow.com/questions/37038830/what-is-the-concept-of-service-container-in-laravel – wujt
https://stackoverflow.com/a/48239728/4701635 –