Laravel - 服务提供商 - 绑定多个班级

时间:2015-08-07 23:08:25

标签: php laravel laravel-5

我知道如何绑定一个类:

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

但想象我的Laracasts\Search\目录有这些文件:

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

将这四个文件/类绑定到搜索门面的最佳方法是什么?

我在另一个non-related question中读到我们可以使用映射器。但是如何?

1 个答案:

答案 0 :(得分:4)

为每个类/门面使用单独的绑定:

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

绑定只能绑定到一件事。当然,在绑定类中,你可以做任何你喜欢的事情:

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