这是一个让我发疯了一个多星期的问题。我通过 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
我的方法有什么问题?