什么是Laravel服务容器?
我在youtube上阅读了此文档以及其他一些信息,但仍然不完全理解什么是服务容器以及如何或何时使用它,因此请您用简单的话解释什么是服务容器以及如何使用什么是Laravel服务容器?,laravel,Laravel,我在youtube上阅读了此文档以及其他一些信息,但仍然不完全理解什么是服务容器以及如何或何时使用它,因此请您用简单的话解释什么是服务容器以及如何使用bind,make,解析等。服务容器用于“控制反转,IoC”的概念 它基本上是一个容器,您可以解析您的服务等 class SomethingInMyApplication { public function __constructor(LoggerInterface $logger) { $logger->info("he
bind
,make
,解析
等。服务容器用于“控制反转,IoC”的概念
它基本上是一个容器,您可以解析您的服务等
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
更改为其他实现
容器基本上检查\u构造函数中的所有参数,并尝试从容器中解析这些类型
$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