
Laravel is a powerful framework and most popular framework nowadays. While working with laravel you many times use Service container but if you still confused about what is concept of the Service Container in Laravel then this article will clear your all doubt and confusion about laravel service container.
Service Container in Laravel
Before start explanation of service container i want to explain a another that is called DI mean Dependency Injection.
What is Dependency Injection?
In software engineering, dependency injection is a technique in which an object receives other objects that it depends on. These other objects are called dependencies. In the typical “using” relationship the receiving object is called a client and the passed object is called a service.
By Wikipedia
In simple word Dependency Injection is passing dependency to other object or framework. Dependency Injection is done by providing dependency into constructor or setter function. Most of the case we use inject it via constructor.
There are number of ways to Inject Dependency –
- Constructor Injection
- Setter Injection
- Interface Injection
Constructor Injection
Class Client {
public $service;
public function __construct(CarService $service){
$this->service = $service;
}
}
Setter Injection
Class Client {
public $service;
public function setService(CarService $service){
$this->service = $service;
}
}
Interface injection
interface Services{
public function setService(CarService $service);
}
Class Client implements Services {
private $service;
public function setService(CarService $service){
$this->service = $service;
}
}
Now you get the point so lets talk about service container.
What is Service Container?
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.
By Laravel
Laravel Documentation is best and well written docs which is easy to read. Lets simplify the term, A Service Container is Container where all Service are Managed by Laravel Core.
It was simple right?
Lets deep dive more.
If you ever try any basic example in Laravel congratulation you already used service container. Lets check a example by doing.
Assume we have a Billing Method Called PaypalAPI and we used this in any controller method via method injection (One of the most used in laravel for example Request $request). Same thing we do in this example.
<?php
namespace App\Billings;
class PaypalAPI
{
public function pay()
{
return [
'amount' => 123,
'transaction_id' => rand(1200121251, 9200121251)
];
}
}
This PHP Class or Service we directly can use in any controller method or callable method why? Its because of Laravel Service Container.
Just Check how we can get it.
<?php
# routes/web.php
use Illuminate\Support\Facades\Route;
Route::get('/', function (\App\Billings\PaypalAPI $api) {
dump($api->pay());
dd(app());
});
in this we not make any instance of PaypalAPI by own we just inject it in function and start using it. now take a look at output of app();
#resolved: array:53 [▼
"events" => true
"router" => true
"App\Http\Kernel" => true
"Illuminate\Contracts\Http\Kernel" => true
"Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables" => true
"Illuminate\Foundation\Bootstrap\LoadConfiguration" => true
"Illuminate\Foundation\Bootstrap\HandleExceptions" => true
"env" => true
"Illuminate\Foundation\Bootstrap\RegisterFacades" => true
"Illuminate\Foundation\PackageManifest" => true
"Illuminate\Foundation\Bootstrap\RegisterProviders" => true
"Facade\Ignition\DumpRecorder\DumpRecorder" => true
"flare.http" => true
"Facade\FlareClient\Flare" => true
"Facade\Ignition\Middleware\SetNotifierName" => true
"Facade\Ignition\Middleware\AddEnvironmentInformation" => true
"Facade\Ignition\LogRecorder\LogRecorder" => true
"Facade\Ignition\Middleware\AddLogs" => true
"Facade\Ignition\Middleware\AddDumps" => true
"Facade\Ignition\QueryRecorder\QueryRecorder" => true
"Facade\Ignition\Middleware\AddQueries" => true
"Facade\IgnitionContracts\SolutionProviderRepository" => true
"Facade\Ignition\Middleware\AddSolutions" => true
"Illuminate\Foundation\Bootstrap\BootProviders" => true
"db.factory" => true
"db" => true
"view.engine.resolver" => true
"files" => true
"blade.compiler" => true
"log" => true
"queue" => true
"cache" => true
"cache.store" => true
"Illuminate\Cache\RateLimiter" => true
"App\Http\Middleware\TrustProxies" => true
"Asm89\Stack\CorsService" => true
"Fruitcake\Cors\HandleCors" => true
"App\Http\Middleware\PreventRequestsDuringMaintenance" => true
"Illuminate\Foundation\Http\Middleware\ValidatePostSize" => true
"App\Http\Middleware\TrimStrings" => true
"Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull" => true
"encrypter" => true
"App\Http\Middleware\EncryptCookies" => true
"cookie" => true
"Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse" => true
"session" => true
"Illuminate\Session\Middleware\StartSession" => true
"view.finder" => true
"view" => true
"Illuminate\View\Middleware\ShareErrorsFromSession" => true
"App\Http\Middleware\VerifyCsrfToken" => true
"Illuminate\Routing\Middleware\SubstituteBindings" => true
"App\Billings\PaypalAPI" => true
]
at the last one. did you notice?
It is Laravel Core Service Container work that its automatic resolve any dependency we use in method, constructor or via interface injection.
We checked the concept of Service Container that provide Zero Configuration Resolution and its help alot to software development.
Now we if you think while reading this article we not provide any details about binding a service because its not a good time to show to both thing about Service Container and Service Provider because it will create a confusing again so we will make a new article to clear the binding and resolving concept via Service Provider.
Conclusion
Let Party now 😂. If you read full guide that i’m sure you cleared most confusing topic about Service Container and Dependency Injection. If you are new in Laravel then you need to clear your basic level but it might help to know how the things are working in Laravel.