Nggawe Laravel Aplikasi karo Dependency Injection

Ing artikel iki, kita bakal mlaku-mlaku mbangun Laravel aplikasi nggunakake Dependency Injection kanggo ngatur dependensi lan nggawe struktur kode sumber luwih maintainable. Kita bakal nggawe conto prasaja ngatur dhaptar produk ing toko.

Langkah 1: Preparation

Kaping pisanan, priksa manawa sampeyan wis Laravel diinstal ing komputer. Sampeyan bisa nggunakake Composer kanggo nggawe proyek anyar Laravel:

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

Sawise nggawe proyek, navigasi menyang direktori proyek:

cd DependencyInjectionApp

Langkah 2: Nggawe Service lan Interface

Ayo dadi miwiti dening nggawe service kanggo ngatur dhaftar produk. Nggawe interface lan kelas sing nindakake iki interface:

Nggawe file app/Contracts/ProductServiceInterface.php:

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

Nggawe file 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  
    }  
}  

Langkah 3: Ndhaptar ing Service Wadhah

Bukak file app/Providers/AppServiceProvider.php lan tambahake menyang register fungsi:

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

Langkah 4: Nggunakake Dependency Injection

Ing controller, sampeyan bisa nggunakake Dependency Injection kanggo nyuntikake ProductService:

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

Kesimpulan

Kanthi nggenepi Dependency Injection lan Service Container ing Laravel, kita wis dibangun aplikasi kanggo ngatur dhaftar produk. Pendekatan iki ndadekake kode sumber luwih bisa dijaga lan nyuda dependensi ing antarane komponen aplikasi sing beda.

Laku lan ngatur proyek miturut kabutuhan kanggo entuk pangerten sing luwih jero babagan nggunakake Dependency Injection ing Laravel.