1

I am new to PHP-DI and I really do not understand what do I miss.

I have a container:

$definitonFile = __DIR__ . '/app/etc/di_config.php';

$containerBuilder = new \DI\ContainerBuilder();
$containerBuilder->useAutowiring(true);
$containerBuilder->addDefinitions($definitonFile);
$container = $containerBuilder->build();
$container->call(["Vendor\MyTestClass", "getName"], []);

In the definition file:

return [
  'Logger' => DI\autowire()->constructor('app.log'),
];

And int the MyTestClass

<?php

namespace Vendor;

use Monolog\Logger;

class MyTestClass
{
    /**
     * @var Logger
     */
    private $logger;

    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
    }

    public function getName()
    {
        var_dump($this->logger);
    }

}

For some reason I am getting this error message:

Fatal error: Uncaught DI\Definition\Exception\InvalidDefinition: Entry "Vendor\MyTestClass" cannot be resolved: Entry "Monolog\Logger" cannot be resolved: Parameter $name of __construct() has no value defined or guessable Full definition: Object ( class = Monolog\Logger lazy = false __construct( $name = #UNDEFINED# $handlers = (default value) array ( ) $processors = (default value) array ( ) ) ) Full definition: Object ( class = Vendor\MyTestClass lazy = false __construct( $logger = get(Monolog\Logger) ) ) in /var/www/dmholding.lh/vendor/php-di/php-di/src/Definition/Exception/InvalidDefinition.php on line 18

I am doing exactly as in the documentation.

Can somebody look at it?

vaso123
  • 12,347
  • 4
  • 34
  • 64

2 Answers2

0

I don't see the Logger class being defined. See this example in the PHP-DI documentation.

<?php
// config.php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

return [
    // ...

    Psr\Log\LoggerInterface::class => DI\factory(function () {
        $logger = new Logger('mylog');

        $fileHandler = new StreamHandler('path/to/your.log', Logger::DEBUG);
        $fileHandler->setFormatter(new LineFormatter());
        $logger->pushHandler($fileHandler);

        return $logger;
    }),
];

http://php-di.org/doc/best-practices.html#using-libraries

serialworm
  • 761
  • 3
  • 13
  • I have only one problem with this. Now it is sit on `Psr\Log\LoggerInterface` so all the logger will use this configuration. Can I somehow define more than one? For example, I want to log into another file, or into another channel. Tell me if you want me to ask it as another question. – vaso123 Jun 03 '19 at 22:11
  • You should be able to do that with the StreamHandler. Here's an example https://seldaek.github.io/monolog/doc/01-usage.html#leveraging-channels – serialworm Jun 03 '19 at 22:15
0
return [
  'Logger' => DI\autowire()->constructor('app.log'),
];

You define Logger as the class name, but it seems that the class you actually inject is Monolog\Logger.

Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261