Imagine we have two classes:
- A Superhero (a toy).
- A Cape (an extra part the superhero needs to fly).
Step-by-Step Breakdown
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(); } }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
}
}
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