Inject array into Controller with Service Container

186 Views Asked by At

I want to provide some default settings to a controller when it is instantiated. My end goal is to provide a dummy object for testing which I can use with registerPaymentMethod on my controller To that end I thought I could provide these via the service container:

public function registerPaymentMethod($name, $class)
{
    $this->methods[$name] = $class;
}

I was unsure whether to use ->bind or ->singleton here.

$this->app->singleton('CheckoutController', function($app)
{
    $controller =  new CheckoutController();
    $controller->registerPaymentMethod('stripe', StripeCheckoutMethod::class);
    return $controller;
});

When I come to call on my $methods array, it is empty. For example the following is called from a route:

public function getCheckoutMethods()
{
    dd($this->methods); //gives []
}

As stated my goal is to inject a dummy object into the controller so I can test the functionality of the controller without calling on a specific CheckoutMethod (which StripeCheckoutMethod implements).

public test_something()
{
   $this->app->singleton('CheckoutController', function($app)
   {
        $controller = new CheckoutController();
        $controller->registerPaymentMethod('dummy_method', MyDummyCheckoutMethod::class);
        return $controller;
   }

   //test things knowing that CheckoutController now has a 'dummy_method'
}

Any guidance appreciated!

1

There are 1 best solutions below

0
On

The answer was an omission my part. I should explicitly provide a fully qualified class:

$this->app->bind('App\Http\Controllers\CheckoutController', function($app)
{
    $controller =  new CheckoutController();
    $controller->registerPaymentMethod('stripe', StripeCheckoutMethod::class);
    return $controller;
});

or

use App\Http\Controllers\CheckoutController;

$this->app->bind(CheckoutController::class, function($app)
{
    $controller =  new CheckoutController();
    $controller->registerPaymentMethod('stripe', StripeCheckoutMethod::class);
    return $controller;
});

Also note that I used bind here rather than singleton