Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DI - cannot be resolved Parameter $logger of __construct() has no value defined or guessable

Tags:

php

php-di

I am trying to get a basic example of PHP-DI work, but I simple to be stuck at a fairly basic example. I assume I am missing something simple here, but have not been able to single it out.

It is not recognising the LoggerInterface type hinting, but that is taken straight out of the examples so I do not understand what I am doing wrong.

The example works fine when I remove LoggerInterface from the Service signature.

Service class:

<?php
namespace test\ServiceLayer;
class TestService extends BaseService{
  public function __construct(\Psr\Log\LoggerInterface $logger){}
}
?>

config.php

<?php
use Monolog\Logger;
return [
    'TestService' => \DI\create(\test\ServiceLayer\TestService::class),
    Psr\Log\LoggerInterface::class => DI\factory(function () {
        $logger = new Logger('mylog');
        return $logger;
    }),
];
?>

usage:

<?php
$builder = new \DI\ContainerBuilder();
$builder->addDefinitions('config.php');
$container = $builder->build();
$service = $container->get('TestService');
?>

Exception:

object(DI\Definition\Exception\InvalidDefinition)#115 (7) {
["message":protected]=> string(196) "Entry "TestService" cannot be resolved: Parameter $logger of __construct() has no value defined or guessable Full definition: Object ( class = arkon\ServiceLayer\TestService lazy = false )"

like image 593
user3159921 Avatar asked Mar 06 '23 13:03

user3159921


1 Answers

You are using create(), if you want the entry to be autowired you need to use autowire() instead.

See this documentation.

like image 90
Matthieu Napoli Avatar answered Apr 07 '23 02:04

Matthieu Napoli