Laravel 8: 有没有办法通过和标识符访问绑定实例?对象缓存的正确方法是什么?

Laravel 8: Is there a way access bound instance via and identifier? And what's the correct way for object caching?

我是 Laravel 的新手。

我的目标是基本上将一些服务 class 实例缓存到 Laravel 容器中,并在需要时检索它们。特别是,我想缓存相同 class 的两个实例两次,并使用字符串标识符来识别它们。

当我使用 app()->bind 函数将实例绑定到容器时,标识符似乎必须是 class 名称,所以基本上我无法区分它们。

这是我在检索服务时想要做的伪代码

class FooHelper {
   function getBarService($serviceClassName, $isMasterDb) {
      $name = $serviceClassName;
      if ($isMasterDb) {
         $name .= 'Master';
      } else {
         $name .= 'Slave';
      }
      if(!bound($name)) {
         $service = new ServiceClass();
         app()->bind($name, $service);
      } else {
         return app($name);
      }
   }
}

我什至不确定使用容器系统缓存服务实例是否正确。

如果有人知道实现上述功能的正确方法,请告诉我。

有关应用程序容器的更多信息,请参阅 documentation 但简短的故事是:

使用 bindsingleton 绑定构造和实例的回调,或将接口绑定到实现它的 class。两者的区别在于singleton会缓存它第一次创建的实例。

如果您已经有了要在容器中“缓存”的实例,那么您将使用 instance 这样您的代码将变为:

class FooHelper {
   function getBarService($serviceClassName, $isMasterDb) {
      $name = $serviceClassName;
      if ($isMasterDb) {
         $name .= 'Master';
      } else {
         $name .= 'Slave';
      }
      if(!bound($name)) {
         $service = new ServiceClass();
         app()->instance($name, $service);
      } else {
         return app($name);
      }
   }
}