Laravel - Service Provider - Bind multiple classes

2019-05-26 22:53发布

问题:

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:

  • Search.php // class Search
  • SearchX.php // class SearchX
  • SearchY.php // class SearchY
  • SearchZ.php // class SearchZ

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?

回答1:

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');