PHP-Laravel依赖注入:将参数传递给依赖构造函数 [英] PHP - Laravel dependency injection: pass parameters to dependency constructor

查看:581
本文介绍了PHP-Laravel依赖注入:将参数传递给依赖构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Laravel项目,并且在其中一个控制器中,我在一种方法中注入了两个依赖项:

I'm building a Laravel project and in one of the controllers I'm injecting two dependencies in a method:

public function pusherAuth(Request $request, ChannelAuth $channelAuth) { ... }

我的问题是简单:如何将参数传递给 $ channelAuth 依赖项?

My question is really simple: How do I pass parameters to the $channelAuth dependency?

此刻我正在使用一些设置器传递所需的依赖项:

At the moment I'm using some setters to pass the needed dependencies:

public function pusherAuth(Request $request, ChannelAuth $channelAuth)
{
    $channelAuth
        ->setChannel($request->input('channel'))
        ->setUser(Auth::user());

此方法有哪些替代方案?

What are the alternatives to this approach?

聚苯乙烯该代码必须是可测试的。

P.S. The code needs to be testable.

推荐答案

感谢我在此 Laracast讨论我能够回答这个问题。使用服务提供商可以通过将正确的参数传递给构造函数来初始化依赖关系。这是我创建的服务提供商:

Thanks to the help I received on this Laracast discussion I was able to answer this question. Using a service provider it's possible to initialize the dependency by passing the right parameters to the constructor. This is the service provider I created:

<?php namespace App\Providers;

use Security\ChannelAuth;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;

class ChannelAuthServiceProvider extends ServiceProvider {

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('Bloom\Security\ChannelAuthInterface', function()
        {
            $request = $this->app->make(Request::class);
            $guard   = $this->app->make(Guard::class);

            return new ChannelAuth($request->input('channel_name'), $guard->user());
        });
    }
}

这篇关于PHP-Laravel依赖注入:将参数传递给依赖构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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