Christopher
Christopher

Reputation: 3469

Laravel - Service Provider - Bind multiple classes

I know how to bind a single class:

public function register() {
    $this->app->bind('search', 'Laracasts\Search\Search');
}

But imagine my Laracasts\Search\ dir having these files:

What is the best way to bind these four files/classes into the search facade?

I read in another non-related question that we can use a mapper. But how?

Upvotes: 2

Views: 5620

Answers (1)

Ben Claar
Ben Claar

Reputation: 3415

Use a separate binding for each class/facade:

public function register() {
    $this->app->bind('search.x', 'Laracasts\Search\SearchX');
    $this->app->bind('search.y', 'Laracasts\Search\SearchY');
    ...
}

A binding can only be bound to one thing. Of course, within the bound class, you can do anything you like:

public function register() {
    $this->app->bind('search.all', 'Laracasts\Search\SearchAll');
}

class SearchAll() {

    private $searchers = []; // an array of searchers

    // Use Laravel Dependency Injection to instantiate our searcher classes
    public function __construct(SearchX $searchX, SearchY $searchY) {
        $this->searchers = [$searchX, $searchY];
    }

    public function search($value) {
        $matches = [];
        foreach ($this->searchers() as $searcher) {
            $matches += $searchers->search();
        }
        return $matches;
    }
}

// elsewhere in your app...
$searcher = app('search.all');
$matches = $searcher->search('hello');

Upvotes: 8

Related Questions