ContainerBuiler::findByType() return Definition, not ServiceDefinition in nette/di 3.0
- Pavel Janda
- Member | 977
Hi,
In Nette 2.4, we had a DIC extension looking like this:
use Psr\Log\LoggerAwareInterface;
class MonologExtension extends CompilerExtension
{
public function beforeCompile(): void
{
$builder = $this->getContainerBuilder();
$logger = $builder->addDefinition($this->prefix('logger'));
foreach ($builder->findByType(LoggerAwareInterface::class) as $service) {
$service->addSetup('setLogger', ['@' . $this->prefix('logger')]);
}
}
}
I can not do that anymore because the $builder->findByType()
call returns Definitnion
and not ServiceDefinition
.
What is the best practise to fix this scenario?
- David Matějka
- Moderator | 6445
in nette 3.0, service definition has been splitted into various container builder definition types and “service definition” is one of them. so just add an instanceof check
- Pavel Janda
- Member | 977
By any chance, is there any documentation site or a blog post abut it?
public function beforeCompile(): void
{
$builder = $this->getContainerBuilder();
$logger = $builder->addDefinition($this->prefix('logger'));
foreach ($builder->findByType(LoggerAwareInterface::class) as $service) {
if ($service instanceof ServiceDefinition) {
$service->addSetup('setLogger', ['@' . $this->prefix('logger')]);
} elseif ($service instanceof FactoryDefinition) {
$service->getResultDefinition()->addSetup('setLogger', ['@' . $this->prefix('logger')]);
} else {
throw new \UnexpectedValueException;
}
}
}
😢😢😢😢
- Marek Bartoš
- Nette Blogger | 1275
assert($service instanceof ServiceDefinition);
should be safe in
most cases. In this case you may also need check FactoryDefinition and
use $service = $service->getResultDefinition()
Edit: I didn't see your answer @PavelJanda. Your solution should be ok
Last edited by Mabar (2019-09-05 15:04)
- Marek Bartoš
- Nette Blogger | 1275
Unfortunatelly not. But feel free to ask me in case something is not
clear.
We may write some articles about it and other things related to migration if you
give us suggestion