In my Laravel project, it seems to me that what I can achieve through a service provider can also be done by the service container without using any service provider.
Let me show how I can achieve the goal using either approach:
Service provider approach:
In my project inside app/Service
I have the files AwesomeServiceInterface.php
and AwesomeService.php
.
Inside AwesomeServiceInterface.php
file, I have :
namespace App\Service;
interface AwesomeServiceInterface
{
public function doAwesomeThing();
}
Inside AwesomeService.php
file , I have :
namespace App\Service;
class AwesomeService implements AwesomeServiceInterface
{
public function doAwesomeThing()
{
echo 'do awesome thing !!!';
}
}
In the config/app.php
file , I have added to the 'providers'
array the following line :
App\Providers\AwesomeServiceProvider::class,
Inside app/Providers
, I have the file AwesomeServiceProvider.php
that contains :
public function register()
{
$this->app->bind('App\Service\AwesomeServiceInterface', 'App\Service\AwesomeService');
}
Inside HomeController.php
, I have :
use App\Service\AwesomeServiceInterface;
........
public function doAwesome(AwesomeServiceInterface $awesome_service)
{
$awesome_service->doAwesomeThing();
return '';
}
In routes/web.php
, I have :
Route::get('/awesome', 'HomeController@doAwesome')->name('awesome');
Now when I hit the URL /awesome
, I get what I expected i.e. do awesome thing !!!
Service container approach :
Without creating any service provider (i.e. AwesomeServiceProvider
), I have inside the register
method of AppServiceProvider.php
at app/Providers
:
public function register()
{
$this->app->bind('App\Service\AwesomeServiceInterface','App\Service\AwesomeService');
}
This time I could also hit the URL /awesome
and get the same output as before.
So Q1) why do I need any service provider in the above scenario ?
Q2) in which case do I need a service provider that I cannot achieve the goal with service container only i.e. without using any service provider ?