Dependency injection Flashcards
What are 2 ways to access services lazily from the DI-Container instead of using autowiring?
- service locator
- public service (not best practice)
How can you make sure the DI-Container is configured in a valid way?
php bin/console lint:container
How can you limit a service to be added to the container only in specific environments?
#[When(env: 'dev')] class SomeClass {
How does Symfony know which Service of an interface to use if there are multiple implementations?
Container is configured to choose one. Also it’s configurable which one to use preferable.
Can closures be injected into services?
Yes! Like this:
class MessageGenerator { private string $messageHash; public function \_\_construct( private LoggerInterface $logger, callable $generateMessageHash, ) { $this->messageHash = $generateMessageHash(); } // ... } services: # ... same code as before # explicitly configure the service App\Service\MessageGenerator: arguments: $logger: '@monolog.logger.request' $generateMessageHash: !closure '@App\Hash\MessageHashGenerator'
How can you set a factory for a class via the configuration file?
services: # ... App\Email\NewsletterManager: # the first argument is the class and the second argument is the static method factory: ['App\Email\NewsletterManagerStaticFactory', 'createNewsletterManager']
How can symfony know which service to inject if the interface is being passed as Typehint?
With an alias in the configuration, showing that the interface targets a specific implementation of that interface
How can you get a list of autowirable names?
bin/console debug:autowiring LoggerInterface
What are lazy services?
Services can be marked as lazy. Then symfony creates a proxy-service, that needs almost no ressources for instantiation. Only if the proxy-service is being called, the actual service will be instantiated. This is resource-saving.
Can be useful if a big service which instantiation need many resources is injected to another service which only calls the injected service in few methods.
How can you mark services as lazy?
In the config
services: App\Twig\AppExtension: lazy: true
or directly when injecting
public function \_\_construct( #[Autowire(service: 'app.twig.app_extension', lazy: true)] ExtensionInterface $extension ) { // ... }
or on the service itself
#[Lazy] class AppExtension implements ExtensionInterface { // ... }