Slim with PHP-DI:无法从自动加载器中找到类



我正试图从与Slim捆绑在一起的疙瘩容器切换到PHP-DI,并且我在获得自动装配工作方面遇到了问题。由于我被限制使用PHP 5.6,我使用Slim 3.9.0和PHP- di 5.2.0以及PHP- di/Slim -bridge 1.1。

我的项目结构如下:

api
- src
|    - Controller
|    |  - TestController.php
|    - Service
|    - Model
|    - ...
- vendor
- composer.json

api/composer.json中,我有以下内容,并运行composer dumpautoload:

{
"require": {
"slim/slim": "3.*",
"php-di/slim-bridge": "^1.1"
},
"autoload": {
"psr-4": {
"MyAPI\": "src/"
}
}
}

我的api/src/Controller/TestController.php文件包含一个类:

<?php
namespace MyAPIController;
class TestController
{ 
public function __construct() 
{

}

public function test($request,$response)
{
return $response->write("Controller is working");
}
}

我最初尝试使用最小的设置来使自动装配工作,只使用默认配置。index.php

<?php
use PsrHttpMessageServerRequestInterface as Request;
use PsrHttpMessageResponseInterface as Response;
require '/../../api/vendor/autoload.php';
$app = new DIBridgeSlimApp;
$app->get('/', TestController::class, ':test');
$app->run();

但是,返回错误:

Type: InvokerExceptionNotCallableException 
Message: 'TestController'is neither a callable nor a valid container entry

我能让它工作的唯一两种方法,是将TestController类直接放在index.php中(这使我认为PHP-DI不能很好地与自动加载器一起使用)或使用DIBridgeSlimApp的以下扩展。然而,由于我需要显式地注册控制器类,这有点违背了使用自动装配的意义(除非我错过了这一点):

use DIContainerBuilder;
use PsrContainerContainerInterface;
use function DIfactory;
class MyApp extends DIBridgeSlimApp
{
public function __construct() {
$containerBuilder = new ContainerBuilder;
$this->configureContainer($containerBuilder);
$container = $containerBuilder->build();
parent::__construct($container);
}
protected function configureContainer(ContainerBuilder $builder)
{
$definitions = [
'TestController' => DIfactory(function (ContainerInterface $c) {
return new MyAPIControllerTestController();
})
];
$builder->addDefinitions($definitions);
}
}
$app = new MyApp();
$app->get('/', ['TestController', 'test']);
$app->run();

如果你想调用测试方法,语法是:

$app->get('/', TestController::class .':test');
// or 
$app->get('/', 'TestController:test');

而不是

$app->get('/', TestController::class ,':test');

cf https://www.slimframework.com/docs/v3/objects/router.html container-resolution

相关内容

  • 没有找到相关文章

最新更新