How do you use Symfony’s Dependency Injection container to create custom services?

How do you use Symfony’s Dependency Injection container to create custom services?

To use Symfony’s Dependency Injection (DI) container to create custom services, follow these minimal steps:

Step 1: Create a Service Class

Define your custom service class.

Example

<?php
namespace App\Service;

class MyCustomService {
    public function doSomething() {
        return "Doing something!";
    }
}
?>

Step 2: Register the Service

In your services.yaml file (located in the config directory), register your service.

Example

services:
    App\Service\MyCustomService:
        # optional: specify arguments here

Step 3: Inject the Service

You can inject the custom service into a controller or another service by type-hinting it in the constructor.

Example

<?php
namespace App\Controller;

use App\Service\MyCustomService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class MyController extends AbstractController {
    private $myCustomService;

    public function __construct(MyCustomService $myCustomService) {
        $this->myCustomService = $myCustomService;
    }

    /**
     * @Route("/do-something", name="do_something")
     */
    public function index(): Response {
        $result = $this->myCustomService->doSomething();
        return new Response($result);
    }
}
?>

Step 4: Use the Service

Now, you can use your custom service in the controller method.

Related Questions & Topics