简体   繁体   English

这是在服务容器中使用依赖项注入的正确方法吗?

[英]Is this the right way to use dependency injection with the Service Container?

So, I have Two different classes: 因此,我有两个不同的类:

Class A A级

class A implements SomeContract
{
    public function extraThicc()
    {
        return 'Filthy Frank';
    } 
}

Class B B级

class B implements SomeContract
{
    public function extraThicc()
    {
        return 'iDubbbz';
    } 
}

Interface 接口

interface SomeContract
{
    public function extraThicc();
}

Boss Class 老板班

class Boss
{
    public $someVar

    public function __construct(SomeContract $someVar)
    {
        $this->someVar = $someVar;
    }
}

The Service Provider 服务提供者

    $this->app->bind('Boss::class', function($app,$param){
        if ($param['type'] == 'A') return new A();
        if ($param['type'] == 'B') return new B();
    });

The Resolving 解决

public function boss($type)
{
    return app()->makeWith('Boss::class', ['type'=>$type')]);
}

The Facade 外立面

class CoolFacade extends Facade
{
    protected static function getFacadeAccessor() { return 'cool'; }
}

The Controller 控制器

class StarWarsBattlefrontController extends Controller
{
    public function index()
    {
        return 'Star Wars: Battlefront 2 Loot Boxes are bad, says:'.Cool::Boss('A')->extraThicc();
    }
}

Is there a better method to inject dependencys into the class? 有没有更好的方法将依赖项注入到类中? Because I don't think this's a good practice to use if statments in the bind method of the Service Provider. 因为我认为这不是在服务提供商的bind方法中使用if语句的好习惯。

Well, your approach isn't really Dependency Injection, but Facades. 好吧,您的方法不是依赖注入,而是Facades。 If you read Laravel Docs on Facades you can see they just describe them as easy accessor, but they should not be abused. 如果您阅读《 立面上的Laravel文档》,您会发现它们只是将它们描述为易于访问的内容,但不应被滥用。 Instead, dependencies must be injected. 相反,必须注入依赖项。

For what you need, you might wanna read on Contextual Binding , which would be something like 对于您所需要的,您可能想阅读Contextual Binding ,它就像

$this->app->when(BossA::class)
          ->needs(SomeContract::class)
          ->give(function () {
              return new A;
          });

$this->app->when(BossB::class)
          ->needs(SomeContract::class)
          ->give(function () {
              return new B;
          });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM