title: Laravel: Different implementations on an instance with Servcie Container
body: <p>In Laravel, how do I resolve 2 different singleton implementations of an instance using Laravel's Service Container (<a href="https://laravel.com/docs/5.7/container" rel="nofollow noreferrer">https://laravel.com/docs/5.7/container</a>).</p>
  
  <p>For example, the 2 implementations I have for a <code>Foo</code> class is:</p>
  
  <pre><code>$this-&gt;app-&gt;singleton(Foo::class, function ($app) {
      return new Foo(config('services.foo.apiKey1'));
  });
  </code></pre>
  
  <p>and</p>
  
  <pre><code>$this-&gt;app-&gt;singleton(Foo::class, function ($app) {
      return new Foo(config('services.foo.apiKey2'));
  });
  </code></pre>
  
  <p>I then have to also resolve it somehow:</p>
  
  <pre><code>$fooV1 = app(Foo::class); // ?
  $fooV2 = app(Foo::class); // ?
  </code></pre>
  
  <p>What is the correct way of writing and resolving 2 different singleton implementations of an instance?</p>
  
  <p><strong>Update</strong></p>
  
  <p>One solution I tried is as follows:</p>
  
  <pre><code>$this-&gt;app-&gt;singleton(Foo::class, function ($app, $parameters) {
      dump('Creating...'); // For testing only to see is actually a singleton
      $apiKey = $parameters[0] ? config('services.foo.apiKey1') : config('services.foo.apiKey2');
      return new Foo($apiKey);
  });
  </code></pre>
  
  <p>and then resolve like so:</p>
  
  <pre><code>$fooV1 = app(Foo::class, [true]);
  $fooV2 = app(Foo::class, [false]);
  </code></pre>
  
  <p>The above also correctly outputs:</p>
  
  <pre><code>Creating...
  Creating...
  </code></pre>
  
  <p>As this is 2 different singletons.</p>
  
  <p>This works for the most part. However, the singleton aspect is not respected. i.e. when creating the same foo twice:</p>
  
  <pre><code>$aV1 = app(Foo::class, [true]);
  $bV1 = app(Foo::class, [true]);
  </code></pre>
  
  <p>Outputs:</p>
  
  <pre><code>Creating...
  Creating...
  </code></pre>
  
  <p>It should have only outputted <code>Created...</code> once in this case, as a Foo with the same set of parameters was already created, thus not being a singleton.</p>