Laravel - Service Provider - Bind multiple classes

2019-05-26 23:00发布

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条回答
Melony?
2楼-- · 2019-05-26 23:05

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');
查看更多
登录 后发表回答