Just started working with symfony 5.3 I read through the documentation about the service container, but it's very confusing.
I understand that in symfony basically everything is a service, but how to tell, when do I need to register my class in the config\services.yaml file?
I don't really understand the connection with the code and that file. This question might be trivial for someone who know how symfony works, but it is confusing for me.
Thanks the clarification in advance.
CodePudding user response:
I try to use sylius and I follow the sylius academy tutorial. MyClass:
class TimeBasedChannelContext implements ChannelContextInterface
{
/** @var ChannelRepositoryInterface */
private ChannelRepositoryInterface $channelRepository;
/** @var ClockInterface */
private ClockInterface $clock;
public function __construct(ChannelRepositoryInterface $channelRepository, ClockInterface $clock)
{
$this->channelRepository = $channelRepository;
$this->clock = $clock;
}
public function getChannel(): ChannelInterface
{
if ($this->clock->isNight()) {
return $this->channelRepository->findOneByCode('NIGHT');
}
return $this->channelRepository->findOneBy([]);
}
}
services.yml:
App\Context\TimeBasedChannelContext:
arguments:
- '@sylius.repository.channel'
- '@App\DateTime\ClockInterface'
tags:
- { name: sylius.context.channel, priority: 1000 }
CodePudding user response:
Symfony introduced the notion of auto-configuration, so you don't have to explicitly declare service. If you look in the default services.yaml
file you can see that all classes in src\
directory are imported automatically:
# config/services.yaml
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class
name
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Tests,Kernel.php}'
Thanks to this configuration, you can automatically use any classes from the src/ directory as a service, without needing to manually configure it.
If you’d prefer to manually wire your service, that’s still totally possible: check how to Explicitly Configuring Services and Arguments.