zoldic's avatar

What is the purpose of using & registering Service Providers?

Hi guys, I'm kinda confuse with Service Providers, I have no idea what is the purpose of using & registering Service Providers (yes, I have read the laravel's doc but I still don't quite get it), it is for calling a class with its method easier

I know how to register class to aliases in config/App.php, and it help you to easier calling the custom class with its method (you don't need to keep importing it with "use namespace" on top of your controller file)

for eg. I make this custom class name called "dump.php" and put it inside new folder called "Customs" (App\Customs\Dump.php)

namespace App\Customs;

class Dump
{
    public static function diedump($var)
    {
        dd($var);
    }
}

register it inside aliases in the config\app.php

'aliases' => [
    ...
    'Dump' => App\Customs\Dump::class,
],

so if I want to use it on one of my controller file, I can simply use the '' to call the class's method (Dump's diedump method)

//use App\Customs\Dump.php;  //don't need to import this anymore

class ThreadController extends Controller
{
    public function index() {
        $var = "dumpthis";
        \Dump::diedump($var);
    }
}

So for the Service Providers, what's the point of registering it? any difference with the aliases?

Can you guys give me simple example & explanatin about it?

Thanks

0 likes
2 replies
florianhusquinet's avatar

A service provider is a class that is used throughout your app without the need to register them on the specific file you need.

For example the RouteServiceProvider is a class laying out the basic configuration for the routing of your application. You can customize it to your need. Another example would be a ViewComposerServiceProvider used to always send a variable to one or multiple view(s). This is useful when you have a partials used on multiple pages and you do not want to worry about querying your database on every controller.

1 like
zoldic's avatar

Hi thanks for the explanation

BTW, can you (or anyone) maybe give me a simple example using my previous example "dump.php" and register it as 'Service Providers', and how to call it, I want to see the difference between registering with 'aliases' and 'Service Providers'

Thanks

Please or to participate in this conversation.