ContainerBuiler::findByType() return Definition, not ServiceDefinition in nette/di 3.0

10 days ago

Pavel Janda
Backer | 857
+
0
-

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?

10 days ago

David Matějka
Moderator | 5949
+
0
-

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

10 days ago

Pavel Janda
Backer | 857
+
+2
-

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;
            }
        }
    }

😢😢😢😢

10 days ago

Mabar
Member | 98
+
0
-

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)

9 days ago

Pavel Janda
Backer | 857
+
0
-

By any chance, is there any documentation site or a blog post abut it?

9 days ago

Mabar
Member | 98
+
0
-

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