How to create service in Symfony?

by muriel.schmidt , in category: PHP Frameworks , 8 months ago

How to create service in Symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 3 months ago

@muriel.schmidt 

To create a service in Symfony, you will need to define it as a class and then register it with the service container. Here is an example of how you can do this:

  1. Define your service class:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// src/Service/MyService.php

namespace AppService;

class MyService
{
    public function doSomething()
    {
        // your service code goes here
    }
}


  1. Register your service with the service container:
1
2
3
4
5
# config/services.yaml

services:
    AppServiceMyService:
        public: true


You can then use your service by asking for it from the service container:

1
2
$myService = $container->get('AppServiceMyService');
$myService->doSomething();


Alternatively, you can use the @ syntax to inject your service as a dependency into a controller or another service:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// src/Controller/MyController.php

namespace AppController;

use AppServiceMyService;
use SymfonyBundleFrameworkBundleControllerAbstractController;

class MyController extends AbstractController
{
    public function myAction(MyService $myService)
    {
        $myService->doSomething();
    }
}


For more information on services and the service container in Symfony, you can refer to the Symfony documentation.