What is Service Container in laravel 9? ,2024

If we want to use one controller class for another controller then we have to use Service Container tools in laravel. means the class dependencies are injected into the class using the constructor or, in some other cases using “setter” methods.

Example:

<?php
 
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
use App\Models\User;
 
class UserController extends Controller
{
    /**
     * The user repository implementation.
     *
     * @var UserRepository
     */
    protected $users;
 
    /**
     * Create a new controller instance.
     *
     * @param  UserRepository  $users
     * @return void
     */
    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }
 
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        $user = $this->users->find($id);
 
        return view('user.profile', ['user' => $user]);
    }
}

In the above example, we need to retrieve all use information from UserRepository in UserController, then the repository is injected using the __construct method.

Binding the data process into the service container

1). Simple Binding concept

Almost all registered of your service container are binding within the service provider.
inside the service provider, you can access the services container via the $this->app property.
are using the bind method to register new service container the clouser has return instance of class.

use App\Services\Transistor;
use App\Services\PodcastParser;
 
$this->app->bind(Transistor::class, function ($app) {
    return new Transistor($app->make(PodcastParser::class));
});

2). Binding A Singleton

The singleton method binds a class or interfaces into the container that should only be resolved one time. Once a singleton binding is resolved, the same object instance will be returned on subsequent calls into the container:

use App\Services\Transistor;
use App\Services\PodcastParser;
 
$this->app->singleton(Transistor::class, function ($app) {
    return new Transistor($app->make(PodcastParser::class));
});

Discover more from STRUGGLER KING.COM

Subscribe now to keep reading and get access to the full archive.

Continue Reading