0

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!

2

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.