WebDev Insights: Explore the World of Web Development and PHP

From Shopware to PHP: Your Resource for Successful E-Commerce

Dependency Injection in PHP: Why and How to Use It in Shopware

What Is Dependency Injection (DI)?

Dependency Injection (DI) is a design pattern that helps manage dependencies in a system. Instead of a class creating its own dependencies, they are passed from the outside.

Why Is Dependency Injection Important?

  • 🔹 Loose Coupling: Modules are more flexible and reusable
  • 🔹 Better Testability: Mocks can be used for unit testing
  • 🔹 Easier Maintenance: Changes to dependencies don’t affect many classes

Dependency Injection in Shopware 6

Shopware 6 uses the Symfony Dependency Injection Container. This means all services are defined in a central configuration.

Example: Creating a Custom Shopware Service with DI

Let's create a ProductService that provides product information:

namespace MyPlugin\Service;

class ProductService {
    public function getProductName(int $id): string {
        return "Product " . $id;
    }
}

Using the Service in a Controller

Thanks to Dependency Injection, we can easily inject the service into a controller:

namespace MyPlugin\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use MyPlugin\Service\ProductService;

class ProductController extends AbstractController {
    private ProductService $productService;

    public function __construct(ProductService $productService) {
        $this->productService = $productService;
    }

    public function showProduct(int $id) {
        return $this->json(['name' => $this->productService->getProductName($id)]);
    }
}

Conclusion

Dependency Injection enables clean, flexible, and testable code. Since Shopware 6 is built on Symfony, using the DI container is the best way to structure code efficiently.

Want to optimize your Shopware projects with Dependency Injection? Contact me – I’d be happy to assist!

Related Articles