Gina Laravel Application da Dependency Injection

A cikin wannan labarin, za mu yi tafiya ta hanyar gina Laravel aikace-aikacen ta yin amfani Dependency Injection da sarrafa abin dogaro da ƙirƙirar tsarin lambar tushe mai inganci. Za mu ƙirƙiri misali mai sauƙi na sarrafa jerin samfura a cikin shago.

Mataki 1: Shiri

Da farko, tabbatar da cewa kun Laravel shigar a kan kwamfutarka. Kuna iya amfani da shi Composer don ƙirƙirar sabon Laravel aiki:

composer create-project --prefer-dist laravel/laravel DependencyInjectionApp

Bayan ƙirƙirar aikin, kewaya zuwa kundin aikin:

cd DependencyInjectionApp

Mataki 2: Ƙirƙiri Service kuma Interface

Bari mu fara da ƙirƙira service don sarrafa jerin samfuran. Ƙirƙiri wani interface aji da ke aiwatar da wannan interface:

Ƙirƙiri fayil ɗin app/Contracts/ProductServiceInterface.php:

<?php  
  
namespace App\Contracts;  
  
interface ProductServiceInterface  
{  
    public function getAllProducts();  
    public function getProductById($id);  
}  

Ƙirƙiri fayil ɗin app/Services/ProductService.php:

<?php  
  
namespace App\Services;  
  
use App\Contracts\ProductServiceInterface;  
  
class ProductService implements ProductServiceInterface  
{  
    public function getAllProducts()  
    {  
        // Logic to get all products  
    }  
  
    public function getProductById($id)  
    {  
        // Logic to get product by ID  
    }  
}  

Mataki 3: Yi rijista a cikin Service kwantena

Bude fayil ɗin app/Providers/AppServiceProvider.php kuma ƙara zuwa register aikin:

use App\Contracts\ProductServiceInterface;  
use App\Services\ProductService;  
  
public function register()  
{  
    $this->app->bind(ProductServiceInterface::class, ProductService::class);  
}  

Mataki na 4: Amfani Dependency Injection

A cikin mai sarrafawa, zaku iya amfani Dependency Injection da allurar ProductService:

use App\Contracts\ProductServiceInterface;  
  
public function index(ProductServiceInterface $productService)  
{  
    $products = $productService->getAllProducts();  
    return view('products.index', compact('products'));  
}  

Kammalawa

Ta amfani Dependency Injection da Service kwantena a cikin Laravel, mun gina aikace-aikace don sarrafa lissafin samfur. Wannan hanya tana sa lambar tushe ta fi kiyayewa kuma tana rage dogaro tsakanin sassa daban-daban na aikace-aikacen.

Yi aiki da tsara aikin bisa ga bukatun ku don samun zurfin fahimtar amfani Dependency Injection a cikin Laravel.