Jagora don Amfani Service Container da Dependency Injection ciki Laravel

Service Container kuma Dependency Injection mahimman ra'ayoyi guda biyu ne Laravel waɗanda ke taimaka muku sarrafa dogaro da tsarin lambar tushen ku da kyau. Da ke ƙasa akwai yadda ake amfani da su a yanayi daban-daban:

SUsing Service Container

The Service Container in Laravel taimaka wajen sarrafa da samar da abubuwa a sassauƙa. Ga yadda ake amfani da Service Container:

Yin Rijista Abu: Yi amfani da bind hanyar don yin rijistar abu cikin Service Container.

app()->bind('userService', function() {  
    return new UserService();  
});  

Shiga Abun: Lokacin da kake buƙatar amfani da abun, zaka iya dawo da shi daga wurin Service Container ta amfani da sunan da aka yi rajista.

$userService = app('userService');

Amfani Dependency Injection

Dependency Injection yana rage dogaro kuma yana sa lambar ku ta zama abin karantawa. Ga yadda ake amfani da su Dependency Injection:

Bayyana Dogara ta hanyar Constructor: A cikin ajin da kuke buƙatar amfani da abin dogaro, bayyana su ta hanyar constructor. Laravel za ta yi allurar dogaro ta atomatik lokacin fara abu.

class UserController extends Controller  
{  
    protected $userService;  
  
    public function __construct(UserService $userService)  
    {  
        $this->userService = $userService;  
    }  
}  

Allurar Dogara ta Setter Hanya: Hakanan zaka iya allurar abin dogaro ta setter hanyoyi. Laravel za ta kira waɗannan hanyoyin ta atomatik don yin allurar abin dogaro.

class UserController extends Controller  
{  
    protected $userService;  
  
    public function setUserService(UserService $userService)  
    {  
        $this->userService = $userService;  
    }  
}  

Kammalawa

Yin amfani Service Container da Dependency Injection ciki yana Laravel taimaka muku sarrafa abubuwan dogaro da tsarin lambar tushe yadda ya kamata. Ta hanyar amfani da waɗannan ƙa'idodin, zaku iya ƙirƙiri mai sassauƙa, mai iya kiyayewa, da sauƙi mai iya ƙarawa yayin haɓaka aikace Laravel -aikacenku.