Laravel PHP

Laravel Service Container Explained, Adding our own class to Laravel Service Container.

Laravel Service Container Explained, Adding our own class to Laravel Service Container.

Laravel is shipped with an effective tool that makes easy the way of managing and inject dependencies. A service container is like a bucket full of all the needed accessories required for a particular task. Every single accessory is bound with a specific name. When any accessory is needed we call it by name and resolve it

Similarly, all the class instances and dependencies are declared within Laravel’s Service Container. Whenever any class instance is needed, we resolve it from the container

To make work our custom classes, we need to bind the class with the “Service Container”
Let’s do some hands-on.

  1. Make a Directory inside “app” directory naming “CustomClasses”
  2. Create a File “CoderWorld.php” and paste the following code.


namespace App\CustomClasses;
 
class CoderWorld
{
   public function sayHello(){
       echo "

Hello From Ghani

"; } }

We’ve created our own custom class. But how Laravel is going to recognize it? Yes we need to bind the class to Laravel’s Service container.

In the “boot” method of AppServiceProvider paste the following code.


  /**
    * Bootstrap any application services.
    *
    * @return void
    */
   public function boot()
   {
       App::singleton('custom-classes', function(){
           return new CoderWorld();
       });
 
   }


By the above code, we created an alias for the CoderWorld class instance and bound it with Laravel’s Service Container by the “custom-classes” string.

Now in the web.php, we write the following code at the bottom.


Route::get('/greet', function(){
   App::make('custom-classes')->sayHello();
});


In the above code, we declared a route for “/greet” and called the sayHello() method from our CoderWorld class. But first, we resolved the class instance by involving the “make” method of the container interface, extended by the “Application” class through “App” facade.

If we go to the “{application_base_url}/greet” then we will find

Hello from ghani

So our code is working fine. This is the way we can create our own custom classes and solve issues with those in an effective way.


Scroll to Top