In this article, we will walk through building a Laravel application using Dependency Injection to manage dependencies and create a more maintainable source code structure. We will create a simple example of managing a product list in a store.
Step 1: Preparation
Firstly, ensure that you have Laravel installed on your computer. You can use Composer to create a new Laravel project:
composer create-project --prefer-dist laravel/laravel DependencyInjectionApp
After creating the project, navigate to the project directory:
cd DependencyInjectionApp
Step 2: Create Service and Interface
Let's start by creating a service to manage the product list. Create an interface and a class that implements this interface:
Create the file app/Contracts/ProductServiceInterface.php
:
<?php
namespace App\Contracts;
interface ProductServiceInterface
{
public function getAllProducts();
public function getProductById($id);
}
Create the 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
}
}
Step 3: Register in the Service Container
Open the file app/Providers/AppServiceProvider.php
and add to the register
function:
use App\Contracts\ProductServiceInterface;
use App\Services\ProductService;
public function register()
{
$this->app->bind(ProductServiceInterface::class, ProductService::class);
}
Step 4: Using Dependency Injection
In the controller, you can use Dependency Injection to inject the ProductService
:
use App\Contracts\ProductServiceInterface;
public function index(ProductServiceInterface $productService)
{
$products = $productService->getAllProducts();
return view('products.index', compact('products'));
}
Conclusion
By utilizing Dependency Injection and the Service Container in Laravel, we have built an application to manage a product list. This approach makes the source code more maintainable and reduces dependencies between different components of the application.
Practice and customize the project according to your needs to gain a deeper understanding of using Dependency Injection in Laravel.