简体   繁体   中英

Dependency injection cannot be handled using php-di

This is a problem that drove me crazy for over one week. I installed php-di via composer and added my own project to the composer.json file:

{
    "name": "mypackage/platform",
    "description": "MyPackage Platform",
    "type": "project",
    "require": {
        "php-di/php-di": "^6.0"
    },
    "autoload": {
        "psr-4": {
            "MyPackage\\": "src/"
        }
    }
}

Then I created mine /public/index.php:

<?php
require_once dirname(__DIR__) . '/vendor/autoload.php';

use DI\ContainerBuilder;
use function DI\create;
use MyPackage\Base\Service;

$containerBuilder = new ContainerBuilder();
$containerBuilder->useAutowiring(false);
$containerBuilder->useAnnotations(false);

$containerBuilder->addDefinitions([
    Service::class => create(Service::class)
]);

$container = $containerBuilder->build();

$service = $container->get('Service');
$service->showMessage();

And this is /src/Base/Service.php content:

<?php

namespace MyPackage\Base;

class Service
{
    public function __construct()
    {

    }

    public function showMessage()
    {
        echo "<BR>Inside Service";
    }
}

When I troy to load index.php, Apache says:

[Thu Dec 05 18:57:47 2019] [error] PHP Fatal error:  Uncaught DI\\NotFoundException: No entry or class found for 'Service' in /var/www/html/vendor/php-di/php-di/src/Container.php:135
Stack trace:
#0 /var/www/html/public/index.php(22): DI\\Container->get('Service')
#1 {main}
  thrown in /var/www/html/vendor/php-di/php-di/src/Container.php on line 135

Whats is wrong with my approach?

$container->get('Service') asks the container for the entry 'Service' . This is a string. There is no namespace.

In your configuration, you configured the service under the Service::class key: Service::class returns the full class name, which is MyPackage\\Base\\Service .

So the error is: you have the service under MyPackage\\Base\\Service , and you try to fetch it via the key Service .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM