Laravel 5.4
Awesome Laravel
- Awesome Laravel (Chirag Gude)
Prologue
- Release Notes
- Upgrade Guide
Getting Started
- Installation
- Configuration
- Directory Structure
- Laravel Homestead
- valet
Architecture Concepts
- Request Lifecycle
- Service Container
- Service Providers
- Facades
The Basics
- Routing
- Errors & Logging
- Middleware
- CSRF Protection
- Controllers
- HTTP Requests
- HTTP Responses
- Views
- HTTP Session
- Validation
Frontend
- Blade Templates
- Localization
- JavaScript & CSS Scaffolding
- Compiling Assets (Laravel Mix)
Security
- Authentication
- API Authentication (Passport)
- Authorization
- Encryption
- Hashing
- Resetting Passwords
Digging Deeper
- Artisan Console
- Queues
- Package Development
- Task Scheduling
- Broadcasting
- Cache
- Collections
- Events
- File Storage
- helpers
- Notifications
Database
- Database Getting Started
- Database Query Builder
- Database Pagination
- Database Migrations
- Database Seeding
- Redis
Eloquent ORM
- Eloquent Getting Started
- Eloquent Relationships
- Eloquent Collections
- Eloquent Mutators
- Eloquent Serialization
Testing
- Testing Getting Started
- HTTP Tests
- Browser Tests (Laravel Dusk)
- Database Testing
- Mocking
- redirect
Official Packages
- Laravel Cashier
- Envoy Task Runner
- Laravel Scout
Service Container
Introduction
The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this: class dependencies are “injected” into the class via the constructor or, in some cases, “setter” methods.
Let’s look at a simple example:
|
In this example, the UserController
needs to retrieve users from a data source. So, we will inject a service that is able to retrieve users. In this context, our UserRepository
most likely uses Eloquent to retrieve user information from the database. However, since the repository is injected, we are able to easily swap it out with another implementation. We are also able to easily “mock”, or create a dummy implementation of the UserRepository
when testing our application.
A deep understanding of the Laravel service container is essential to building a powerful, large application, as well as for contributing to the Laravel core itself.
Binding
Binding Basics
Almost all of your service container bindings will be registered within service providers, so most of these examples will demonstrate using the container in that context.
{tip} There is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects, since it can automatically resolve these objects using reflection.
Simple Bindings
Within a service provider, you always have access to the container via the $this->app
property. We can register a binding using the bind
method, passing the class or interface name that we wish to register along with a Closure
that returns an instance of the class:
Note that we receive the container itself as an argument to the resolver. We can then use the container to resolve sub-dependencies of the object we are building.
Binding A Singleton
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:
Binding Instances
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:
Binding Primitives
Sometimes you may have a class that receives some injected classes, but also needs an injected primitive value such as an integer. You may easily use contextual binding to inject any value your class may need:
Binding Interfaces To Implementations
A very powerful feature of the service container is its ability to bind an interface to a given implementation. For example, let’s assume we have an EventPusher
interface and a RedisEventPusher
implementation. Once we have coded our RedisEventPusher
implementation of this interface, we can register it with the service container like so:
This statement tells the container that it should inject the RedisEventPusher
when a class needs an implementation of EventPusher
. Now we can type-hint the EventPusher
interface in a constructor, or any other location where dependencies are injected by the service container:
Contextual Binding
Sometimes you may have two classes that utilize the same interface, but you wish to inject different implementations into each class. For example, two controllers may depend on different implementations of the Illuminate\Contracts\Filesystem\Filesystem
contract. Laravel provides a simple, fluent interface for defining this behavior:
Tagging
Occasionally, you may need to resolve all of a certain “category” of binding. For example, perhaps you are building a report aggregator that receives an array of many different Report
interface implementations. After registering the Report
implementations, you can assign them a tag using the tag
method:
Resolving
The make
Method
You may use the make
method to resolve a class instance out of the container. The make
method accepts the name of the class or interface you wish to resolve:
If you are in a location of your code that does not have access to the $app
variable, you may use the global resolve
helper:
Automatic Injection
Alternatively, and importantly, you may simply “type-hint” the dependency in the constructor of a class that is resolved by the container, including controllers, event listeners, queue jobs, middleware, and more. In practice, this is how most of your objects should be resolved by the container.
For example, you may type-hint a repository defined by your application in a controller’s constructor. The repository will automatically be resolved and injected into the class:
|
Container Events
The service container fires an event each time it resolves an object. You may listen to this event using the resolving
method:
As you can see, the object being resolved will be passed to the callback, allowing you to set any additional properties on the object before it is given to its consumer.