Laravel What is the use of service providers for laravel

Viewed 21547

l am just getting start of Laravel, and l really confused about service contains and service providers l searched for some examples like follow's service code:

namespace App\Service;


class Tests
{
    public function test()
    {
        echo "aaa";
    }
}

serveice provider's code

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class TestServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
        $this->app->bind('App\Service\Tests', function($app){
            return new \App\Service\Tests();
        });
    }
}

Then l added this provider into config/app,php -> providers Then l create a controller

namespace App\Http\Controllers\test;

use App\Http\Controllers\Controller;
use App\Service\Tests as tests;

class Test extends Controller
{
    public function index()
    {
        $t = new tests();
        $t -> test();
    }
}

So, l can use my Tests like this, why l need to use it by Dependency injection like official site like:

public function index(tests $test)
{
    $test->test();
}

l saw some document or article about DI and IoC, but, but l just couldn't understand what is the use and the benefit about it

2 Answers

First of all, Laravel uses service container and service providers, not server container or server provider :)

Here are some benefits of using dependencies injection (DI):

Simplify the object creation

Because your Test class constructor is quite simple, you don't see the benefit of dependencies injection. Think about a class like this:

class Complex {
    public function __construct(
        FooService $fooService,
        BarService $barService,
        int $configValue
    ) {

    }
}

Without DI, you have to get (or create) instances of $fooService and $barService, retrieve the value of $configValue from the configuration files every time you want a new instance of the Complex class.

With DI, you tell the service container how to create the Complex instance once, then the container can give the correct instance for you with one call (e.g. $container->make(Complex::class))

Manage the couplings between your classes

Continue with the previous example. What happens if the FooService and BarService depends on other classes, too?

Without DI, you have to create instances of the dependent objects (and hope that they do not depends on other classes). This usually ends with multiple instances of one class created, a waste of codes and computer memory.

With DI, all dependent objects are created by the container (you have to register those classes with the container before). The container also manages to keep only one instance of each class if you want, which save the amount of code as well as the amount of memory used by your program.

Only use one instance of your classes when registering with singleton

To keep only one instance of the class in the whole life of the current request, you can register your class creation process with singleton method instead of bind

Service providers for laravel

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.

But, what do we mean by "bootstrapped"? In general, we mean registering things, including registering service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application.

If you open the config/app.php file included with Laravel, you will see a providers array. These are all of the service provider classes that will be loaded for your application. Of course, many of these are "deferred" providers, meaning they will not be loaded on every request, but only when the services they provide are actually needed.

Imagine you have created a class which requires multiple dependencies and in general, you use it like this:

$foo = new Foo(new Bar(config('some_secret_key')), new Baz(new Moo(), new 
Boo()), new Woo('yolo', 5));

it's doable, but you wouldn't want to figure out these dependencies every time you try to instantiate this class. That's why you want to use a service provider wherein the register method you can define this class as:

$this->app->singleton('My\Awesome\Foo', function ($app) {
   return new Foo(new Bar(config('some_secret_key')), new Baz(new Moo(), new 
   Boo()), new Woo('yolo', 5));
});

This way, if you need to use this class, you can just type hint it in the controller (container will figure it out) or ask for it manually like

$foo = app(My\Awesome\Foo::class). Isn't that easier to use? ;)

below Link will guide you how to write your own service providers and register them and use with your Laravel application.

https://laravel.com/docs/5.7/providers

Related