Kujenga Laravel Maombi na Dependency Injection

Katika makala haya, tutapitia kuunda Laravel programu kwa kutumia Dependency Injection kudhibiti utegemezi na kuunda muundo wa msimbo wa chanzo unaodumishwa zaidi. Tutaunda mfano rahisi wa kusimamia orodha ya bidhaa kwenye duka.

Hatua ya 1: Maandalizi

Kwanza, hakikisha kuwa umesakinisha Laravel kwenye kompyuta yako. Unaweza kutumia Composer kuunda Laravel mradi mpya:

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

Baada ya kuunda mradi, nenda kwenye saraka ya mradi:

cd DependencyInjectionApp

Hatua ya 2: Unda Service na Interface

Wacha tuanze kwa kuunda service ili kudhibiti orodha ya bidhaa. Unda interface na darasa ambalo linatekelezea hii interface:

Unda faili app/Contracts/ProductServiceInterface.php:

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

Unda faili 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  
    }  
}  

Hatua ya 3: Sajili kwenye Service Chombo

Fungua faili app/Providers/AppServiceProvider.php na uongeze kwenye register kazi:

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

Hatua ya 4: Kutumia Dependency Injection

Katika kidhibiti, unaweza kutumia Dependency Injection kuingiza ProductService:

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

Hitimisho

Kwa kutumia Dependency Injection na Service Kontena katika Laravel, tumeunda programu ya kudhibiti orodha ya bidhaa. Mbinu hii hufanya msimbo wa chanzo kudumishwa zaidi na hupunguza utegemezi kati ya vipengele tofauti vya programu.

Fanya mazoezi na ubinafsishe mradi kulingana na mahitaji yako ili kupata ufahamu wa kina wa kutumia Dependency Injection katika Laravel.