Categories
symfony symfony 5

Services in Symfony

What is service? In fact, there is a rather simple idea behind this term: a service is any object that does some work. For example, it sends messages, saves data to a database, parses RSS, etc.

How to use the services? Just inside the controller, add an extra argument to the method and give it a type hint like LoggerInterface and name it whatever you want, like $logger:

public function index(LoggerInterface $logger)
{
    // do something
    $logger->info('Some message');
}

How does it work? Before starting the controller, Symfony checks each argument, looks at the type hint, and realizes that we need this or that object. And by the way, the order of the arguments is not important at all.

Symfony comes with a ton of services. How do I know what services are available? Go to the root directory of the project and run the command

bin/console debug:autowiring

Where do service objects come from? Each service is stored inside another object called a container (also called a service container or dependency injection container). An important point: the service object is created only when you request it. If this does not happen, then the service will not be created, which helps to save memory and speed. In addition, the service is created only once, i.e. Symfony will return the same service instance every time.

How do services get into the container, who puts them there? Answer: bundles. Bundles are like plugins in other software. The key difference is that everything in Symfony is bundled, including both the core of the framework and the code written for your application.

If you want to create the service dynamically you can use this code sample:

class Router implements ServiceSubscriberInterface {
private $locator;
public function __construct(ContainerInterface $locator) {
  $this->locator = $locator;
}
 
public static function getSubscribedServices() {
return [
  'foo' => FooService::class,
  'bar' => BarService::class,
];
}
 
public function match($params) {
  if ($this->locator->has($params) {
    $someService = $this->locator->get($params);
  return $someService;
  }
return null;
}
 
}

Good luck!