Jan 5, 2016
0
Level 5
Binding an instance of a class into the service container
Say I want to use the Omnipay php library in my Laravel app. The docs say to use the basic usage is as follows:
// Create a gateway for the Stripe Gateway
// (routes to GatewayFactory::create)
$gateway = Omnipay::create('Stripe');
// Initialise the gateway
$gateway->initialize(array(
'apiKey' => 'MyApiKey',
));
// Do a purchase transaction on the gateway
$transaction = $gateway->purchase(array(
'amount' => '10.00',
'currency' => 'USD',
'card' => $card,
));
// etc
The thing is, the process of instantiating a Stripe version of Omnipay and setting the Api key is one which I'd like to avoid doing in the controller.
Is this something I can do in a Service Provider and then just resolve it out of the IoC container. E.g.
// OrdersController.php
/**
* Create a new order
* @param GatewayInterface $gateway Some sort of Gateway???
* Probably the GatewayInterface that comes in omnipay/common
*/
public function store(GatewayInterface $gateway)
{
// create the order, get card details etc...
$gateway->purchase(
//...
);
// etc
}
So my Gateway is automatically injected into the controller method as a Stripe instance with Api key already set.
How would my service provider do this?
Please or to participate in this conversation.