Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 6 - Bind array of implementations in constructor

I'm trying to inject an array of implementations of a certain interface to a subscriber class.

This is the code in my service provider:

$this->app->tag([TrackerServiceOne::class, TrackerServiceTwo::class], 'trackers');
$this->app->bind(EventSubscriber::class, function ($app) {
    return new EventSubscriber($this->app->tagged('trackers'));
});

And this is the constructor in my EventSubscriber class:

public function __construct(array $trackers)
{
    $this->trackers = $trackers;
}

This is the error I'm getting:

Unresolvable dependency resolving [Parameter #0 [ <required> array $trackers ]] in class Path\To\EventSubscriber
like image 477
Germán Medaglia Avatar asked Oct 30 '25 02:10

Germán Medaglia


1 Answers

Try resolving the EventSubscriber using makeWith from the service container rather than instantiating a new instance:

$this->app->bind(EventSubscriber::class, function ($app) {
    return $app->makeWith(EventSubscriber::class, [
        'trackers' => $this->app->tagged('trackers')
    ]);
});

This should correctly inject the $trackers parameter into the EventSubscriber's constructor.

From the Docs:

If some of your class' dependencies are not resolvable via the container, you may inject them by passing them as an associative array into the makeWith method:

$api = $this->app->makeWith('HelpSpot\API', ['id' => 1]);


Update

After playing around with Laravel 6, I managed to get this working, albeit not quite as described in the documentation:

app()->bind('TrackerServiceOne', function () {
  return new TrackerServiceOne();
});

app()->bind('TrackerServiceTwo', function () {
  return new TrackerServiceTwo();
});

app()->tag([
  'TrackerServiceOne', 
  'TrackerServiceTwo'
], 'trackers');

app()->bind(EventSubscriber::class, function () {
  $trackers = [];

  foreach (app()->tagged('trackers') as $tracker) {
    $trackers[] = $tracker;
  }

  return new EventSubscriber($trackers);
});

$subscriber = resolve(EventSubscriber::class);

dd($subscriber->getTrackers());

Laravel Playground Example

like image 175
Brian Lee Avatar answered Oct 31 '25 18:10

Brian Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!