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) { ... }   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.
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());         });     } } 
                        You can pass parameters (as a string indexed array) when resolving a dependence like this:
<?php namespace App\Providers;  use Security\ChannelAuth; use Illuminate\Contracts\Auth\Guard; 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($params)         {             $channelName = $params['channelName'];             $guard   = $this->app->make(Guard::class);              return new ChannelAuth($channelName, $guard->user());         });     } }   Then when resolving eg in a controller:
public function pusherAuth() {     $channelAuth = app()->makeWith('Bloom\Security\ChannelAuthInterface', [         'channelName' => $request->input('channel_name')     ]);     // ... use $channelAuth ... } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With