Service Container
Last updated
Last updated
[[toc]]
The Goravel service container is a powerful tool for managing class dependencies and performing dependency injection. It contains all the modules of Goravel, and allows you to bind your own services to container and resolve them when needed. The service container provides powerful support for third-party packages around Goravel.
Almost all of your service container bindings will be registered within . Within a service provider, you always have access to the container via the app
parameter, then register a binding using the Bind
method, passing the key
that we wish to register along with a closure that returns an instance of the class:
As mentioned, you will typically be interacting with the container within service providers; however, if you would like to interact with the container outside of a service provider, you may do so via the App
facade:
The Singleton
method binds a class or interface into the container that should only be resolved one time. Once a singleton binding is resolved, the same object instance will be returned on subsequent calls into the container:
You may also bind an existing object instance into the container using the Instance
method. The given instance will always be returned on subsequent calls into the container:
If you need some extra parameters to construct the service provider, you can use the BindWith
method to pass parameters to the closure:
Make
MethodYou may use the Make
method to resolve a class instance from the container. The Make
method accepts the key
you wish to resolve:
If you are outside of a service provider in a location of your code that does not have access to the app
variable, you may use the App
facade to resolve a class instance from the container:
MakeWith
MethodIf some of your class's dependencies are not resolvable via the container, you may inject them by passing them as an associative array into the MakeWith
method, corresponding to the BindWith
binding method:
The framework providers some convenient methods to quickly resolve various facade
: MakeArtisan
, MakeAuth
, MakeCache
, MakeConfig
, MakeCrypt
, MakeEvent
, MakeGate
, MakeGrpc
, MakeHash
, MakeLog
, MakeMail
, MakeOrm
, MakeQueue
, MakeRateLimiter
, MakeRoute
, MakeSchedule
, MakeStorage
, MakeValidation
.