Hello artisan, PHP is the most used server-side programming language on the web. In fact, 75 to 77% of all websites rely on PHP to some degree. And Laravel is one of the most popular framework based on PHP language.
Laravel provides lots of pre build features that user can use easily, Today in this article I’ll explain main difference between Service Container and Service Provider.
As per official definition from Laravel,
- Service Container is a powerful tool for managing class dependencies and performing dependency injection.
- Service Providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel’s core services, are bootstrapped via service providers.
Now let’s understand both in detail,
- Service Container:
Service container is the place where your services are registered.
Laravel comes with a powerful IoC container, known as the service container. In Laravel application, the app instance is the container. The app() helper also returns an instance of the container.
It has basically three methods bind(), make() and singleton() used for binding services, retrieving services and binding class as a singleton respectively.
Let’s understand this methods by example:
app()->bind('App\Interfaces\NewPostMailService', function() {
return new App\Services\NewPostMailService();
});dd(app()->make('App\Interfaces\NewPostMailService'), app()->make('App\Interfaces\NewPostMailService'));==> Above line will return you two different instances.
--------------------------------------------------------------------
app()->singleton('App\Interfaces\NewPostMailService', function() {
return new App\Services\NewPostMailService();
});dd(app()->make('App\Interfaces\NewPostMailService'), app()->make('App\Interfaces\NewPostMailService'));==> Above line will return you same instance because it is registered as singleton.
You can bind any custom services you want in container.
Now where will you put all of these method calls or bindings? The solution is the Service Provider. Let’s understand what is Service Provider.
2. Service Provider:
Service providers provide services by adding them to the container.
In Laravel Service Providers are located in app/Providers Directory.
By default every Laravel project comes with 5 Service Provider, out of them AppServiceProvider is empty class where you can register you binding in register() method.
Each Service Provider has 2 default method register() and boot().
register() method is used for registering new services to the application.
Best custom use of register method is implementation of Repository pattern.
public function register()
{
$this->app->bind(OrderRepositoryInterface::class, OrderRepository::class);
}
boot() method is used for the bootstrapping the registered service, This method is called after all other service providers have been registered.
Best use case of boot() method is View Composers.
public function boot()
{
View::composer('view', function () {
// Add data here
});
}
That’s it! If you have any other questions, please feel free to leave your thoughts in the comments below and don’t forget to clap if you liked it!
The Service container is the place our application bindings
are stored. And service providers are the classes where we register our bindings to the service container. In older releases of Laravel, we didn't have these providers and developers were always asking where to put the bindings. And the answer was confusing: "Where it makes the most sense."(!) Then, Laravel introduced these service providers and the Providers directory to make things more consistent.
Here is a basic example:
interface AcmeInterface {
public function sayHi();
}
class AcmeImplementation implements AcmeInterface {
public function sayHi() {
echo 'Hi!';
}
}
$app = new \Illuminate\Database\Container;
$app->singleton('app', 'Illuminate\Container\Container');
$app->singleton('config', 'Illuminate\Config\Repository');
$app->bind(AcmeInterface::class, AcmeImplementation::class);
$implementation = $app->make(AcmeInterface::class);
$implementation->sayHi();
As you can see:
- first, we create the container (in real life, Laravel does this for us inside
bootstrap/app.php
), - then, we register our service (inside our Service Provider classes, and
config/app.php
), - and finally, we get and use our registered service. (inside controllers, models, services, etc.)
vel, the Service Container is a powerful tool for managing class dependencies and performing dependency injection. It's essentially a registry for all the services (dependencies) used within your application. Let's walk through an example to understand how the Service Container works and how dependencies are registered and resolved.
Let's say we have a simple Laravel application where we want to create a service that calculates the area of a rectangle. We'll create a service provider to register this service and use the Service Container to resolve and use it.
Create a Service Provider:
First, let's create a service provider using Artisan:
php artisan make:provider RectangleAreaServiceProvider
This will generate a new service provider file RectangleAreaServiceProvider.php
in the app/Providers
directory.
Define the Service:
In the RectangleAreaServiceProvider.php
file, define the service and register it in the register
method of the provider:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\RectangleAreaCalculator;
class RectangleAreaServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('rectangleArea', function ($app) {
return new RectangleAreaCalculator();
});
}
}
Here, we're binding the rectangleArea
key to an instance of RectangleAreaCalculator
in the Service Container.
Create the Service Class:
Next, create the RectangleAreaCalculator
class in the app/Services
directory:
<?php
namespace App\Services;
class RectangleAreaCalculator
{
public function calculate($length, $width)
{
return $length * $width;
}
}
This class contains a calculate
method that calculates the area of a rectangle based on its length and width.
Use the Service:
Now, you can use the rectangleArea
service anywhere in your application. For example, in a controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\RectangleAreaCalculator;
class RectangleController extends Controller
{
public function calculateArea(Request $request, RectangleAreaCalculator $rectangleArea)
{
$length = $request->input('length');
$width = $request->input('width');
$area = $rectangleArea->calculate($length, $width);
return response()->json(['area' => $area]);
}
}
In this controller method, we inject the RectangleAreaCalculator
service using Laravel's automatic dependency injection. The calculateArea
method takes the length and width of a rectangle from the request and calculates its area using the injected service.
Register the Service Provider:
Finally, register the RectangleAreaServiceProvider
in the config/app.php
file under the providers
array:
'providers' => [
App\Providers\RectangleAreaServiceProvider::class,
],
This tells Laravel to load and use our custom service provider.
Now, when you call the calculateArea
endpoint in your application, Laravel will automatically resolve the RectangleAreaCalculator
service from the Service Container and use it to calculate the area of a rectangle.
No comments:
Post a Comment