Laravel-服务提供商-绑定多个类 [英] Laravel - Service Provider - Bind multiple classes

查看:70
本文介绍了Laravel-服务提供商-绑定多个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何绑定单个类:

I know how to bind a single class:

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

但是想像一下我的Laracasts\Search\目录具有以下文件:

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

  • Search.php//类Search
  • SearchX.php//类SearchX
  • SearchY.php//类SearchY
  • SearchZ.php//类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?

推荐答案

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

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

这篇关于Laravel-服务提供商-绑定多个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆