Bini ta’ Laravel Applikazzjoni ma’ Dependency Injection

F'dan l-artikolu, aħna se nimxu permezz tal-bini ta ' Laravel applikazzjoni billi tuża Dependency Injection biex timmaniġġja d-dipendenzi u noħolqu struttura ta' kodiċi tas-sors aktar li tista' tinżamm. Aħna se noħolqu eżempju sempliċi ta 'ġestjoni ta' lista ta 'prodotti f'maħżen.

Pass 1: Preparazzjoni

L-ewwelnett, kun żgur li tkun Laravel installat fuq il-kompjuter tiegħek. Tista' tuża Composer biex toħloq proġett ġdid Laravel:

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

Wara li toħloq il-proġett, innaviga fid-direttorju tal-proġett:

cd DependencyInjectionApp

Pass 2: Oħloq Service u Interface

Nibdew billi noħolqu service biex timmaniġġja l-lista tal-prodotti. Oħloq interface klassi u li timplimenta dan interface:

Oħloq il-fajl app/Contracts/ProductServiceInterface.php:

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

Oħloq il-fajl 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  
    }  
}  

Pass 3: Irreġistra fil- Service Kontenitur

Iftaħ il-fajl app/Providers/AppServiceProvider.php u żid register mal-funzjoni:

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

Pass 4: L-użu Dependency Injection

Fil-kontrollur, tista' tuża Dependency Injection biex tinjetta ProductService:

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

Konklużjoni

Bl-użu Dependency Injection u l- Service Kontenitur fi Laravel, bnejna applikazzjoni biex timmaniġġja lista ta 'prodotti. Dan l-approċċ jagħmel il-kodiċi tas-sors aktar manutenzjoni u jnaqqas id-dipendenzi bejn il-komponenti differenti tal-applikazzjoni.

Ipprattika u tippersonalizza l-proġett skont il-bżonnijiet tiegħek biex tikseb fehim aktar profond tal-użu Dependency Injection fil- Laravel.