依赖注入无法使用php-di

时间:2019-12-05 18:05:27

标签: php dependency-injection autoload php-di

这个问题使我疯狂了一个多星期。我通过composer安装了php-di,并将自己的项目添加到composer.json文件中:

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

然后我创建了我的/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();

这是/src/Base/Service.php的内容:

<?php

namespace MyPackage\Base;

class Service
{
    public function __construct()
    {

    }

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

当我尝试加载index.php时,Apache说:

[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

我的方法有什么问题?

1 个答案:

答案 0 :(得分:0)

$container->get('Service')向容器询问条目'Service'。这是一个字符串。没有名称空间。

在配置中,您使用Service::class键配置了服务:Service::class返回完整的类名,即MyPackage\Base\Service

因此错误是:您在MyPackage\Base\Service下拥有服务,并且尝试通过密钥Service来获取它。