We can use the Service Container as a Dependency Injection Container by binding the creation process of objects with their dependencies in one point of the application
Let's suppose that the creation of a PdfCreator
needs two objects as dependencies; every time we need to build an instance of PdfCreator
, we should pass these dependencies to che constructor. By using the Service Container as DIC, we define the creation of PdfCreator
in the binding definition, taking the required dependency directly from the Service Container:
App:bind('pdf-creator', function($app) {
// Get the needed dependencies from the service container.
$pdfRender = $app->make('pdf-render');
$templateManager = $app->make('template-manager');
// Create the instance passing the needed dependencies.
return new PdfCreator( $pdfRender, $templateManager );
});
Then, in every point of our app, to get a new PdfCreator
, we can simply do:
$pdfCreator = App::make('pdf-creator');
And the Service container will create a new instance, along with the needed dependencies for us.