sia*_*one 16 php dependency-injection
我正在构建一个Laravel项目,在一个控制器中,我在一个方法中注入了两个依赖项:
public function pusherAuth(Request $request, ChannelAuth $channelAuth) { ... }
Run Code Online (Sandbox Code Playgroud)
我的问题很简单:如何将参数传递给$channelAuth
依赖项?
目前我正在使用一些setter传递所需的依赖项:
public function pusherAuth(Request $request, ChannelAuth $channelAuth)
{
$channelAuth
->setChannel($request->input('channel'))
->setUser(Auth::user());
Run Code Online (Sandbox Code Playgroud)
这种方法有哪些替代方案?
PS代码需要是可测试的.
sia*_*one 15
感谢我在Laracast讨论中获得的帮助,我能够回答这个问题.使用服务提供程序,可以通过将正确的参数传递给构造函数来初始化依赖项.这是我创建的服务提供商:
<?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());
});
}
}
Run Code Online (Sandbox Code Playgroud)