我知道如何绑定一个类:
public function register() {
$this->app->bind('search', 'Laracasts\Search\Search');
}
但想象我的Laracasts\Search\
目录有这些文件:
将这四个文件/类绑定到搜索门面的最佳方法是什么?
我在另一个non-related question中读到我们可以使用映射器。但是如何?
答案 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');