Dependency Injection

In version 2.0 the namespace was changed from Tomahawk\DI to Tomahawk\DependencyInjection

The Dependency Injection (DI) component allows you to define the way objects are constructed in your application.

Adding single services to the DI Container.

The easiest way to add services is to do it in a Bundle. You can read more about them here.

Below is an example of adding a service to the DI Container:

What if your service required another service as a parameter, well you just need to pass the second parameter as a closure:

The above examples will return the same object each time, if you wanted to return a different object every time you got it out of the DI container you can do:

Creating a Service Provider

To create a service provider you need to implement the Tomahawk\DependencyInjection\ServiceProviderInterface interface.

The ServiceProviderInterface only has one method called register to implement.

You remember the services we registered in the Bundle earlier, this can be replaced with the service provider instead: