Sunday, 6 October 2024

Explain Laravel's service container and dependency injection

Imagine we have two classes:

  1. A Superhero (a toy).
  2. A Cape (an extra part the superhero needs to fly).

Step-by-Step Breakdown

  1. Superhero Class (Needs a Cape):

    class Superhero { protected $cape; // Superhero needs a Cape to fly public function __construct(Cape $cape) { $this->cape = $cape; } public function fly() { return "Flying with a " . $this->cape->type(); } }
  2. Cape Class (The Extra Part):

    class Cape { public function type() { return 'red cape!'; } }

Bind Superhero and Cape in the service provider

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ToyStoreServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        // Binding Cape class
        $this->app->bind(Cape::class, function () {
            return new Cape();
        });

        // Binding Superhero class, which depends on Cape
        $this->app->bind(Superhero::class, function ($app) {
            return new Superhero($app->make(Cape::class));
        });
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        // Any bootstrapping code can go here
    }
}


Resolving the Classes

Now, when you resolve the Superhero, Laravel will automatically create the Cape instance since you’re creating it directly in the closure of the Superhero binding:

$superhero = app(Superhero::class); echo $superhero->fly(); // Output: "Flying with a red cape!"

Thank you

No comments:

Post a Comment

Golang Advanced Interview Q&A